Vue2 axios 携带Cookies跨域请求 后台.net core1.1

Vue2 axios 携带Cookies跨域请求

  • 后台 .net core v1.1
  • axios v0.16.2
  • 前端框架Vue 2.3.3

前端代码 axios

  • 设置 withCredentials: true
  • 就是要在原来的请求中设置这个属性为true就可以
// 需要验证的才能请求的数据
postTest() {
  this.$axios({
    method: 'get',
    url: 'http://localhost:65284/Home/tabdata',
    withCredentials: true
  }).then(sss => {
    console.log(sss.data)
  })
}
// 登陆获取cookies
let data = new FormData()
data.append('userFromFore.userName', 'peach')
data.append('userFromFore.Password', '112233')
this.$axios({
  method: 'post',
  url: 'http://localhost:65284/Account/login',
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data: data,
  withCredentials: true
}).then(response => {
  console.log('OK')
  this.postTest()
})

后台代码

  • 需要安装两个包

  • 登陆参考 http://www.cnblogs.com/onecodeonescript/p/6015512.html

  • 跨域的参考 不记得是哪一篇下次补上

  • 配置这些只要在需要的 Controller 请求添加 [EnableCors("MyDomain")]允许跨域注释 [Authorize] 需要登录验证注释

  • 需要注意的是我在测试过程中 Home/index 一定要加允许跨域注释,不然提示受控制访问不了登陆请求(可能是我的配置不对)

Startup.cs文件配置

public void ConfigureServices(IServiceCollection services)
{
    // 跨域请求设置 
    var urls = "http://localhost:/"; // 还没有研究这个什么我设置的是我的访问路径
    services.AddCors(options =>
    options.AddPolicy("MyDomain",
        builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
    // mvc设置
    services.AddMvc();

    // 身份验证
    services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// 身份验证
app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
    AuthenticationScheme = "Cookie",
    LoginPath = new PathString("/Account/Login"),// 登陆路径 , 如果没有登陆跳转到的登陆路径
    AccessDeniedPath = new PathString("/Account/Forbidden"), //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
    AutomaticAuthenticate = true, //自动认证:这个标志表明中间件应该会在每个请求上进行验证和重建他创建的序列化主体。  
    AutomaticChallenge = true, //自动挑战:这个标志标明当中间件认证失败时应该重定向浏览器到登录路径或者禁止访问路径。
    SlidingExpiration = true,  //Cookie可以分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 永久性的是指Cookie指定了一个过期时间,在这个时间到达之前,此cookie一直有效(浏览器一直记录着此cookie的存在)。 slidingExpriation的作用是,指示浏览器把cookie作为永久性cookie存储,但是会自动更改过期时间,以使用户不会在登录后并一直活动,但是一段时间后却自动注销。也就是说,你10点登录了,服务器端设置的TimeOut为30分钟,如果slidingExpriation为false,那么10:30以后,你就必须重新登录。如果为true的话,你10:16分时打开了一个新页面,服务器就会通知浏览器,把过期时间修改为10:46。 更详细的说明还是参考MSDN的文档。
  });
}

AccountController.cs 文件

    public class AccountController : Controller
    {
        // GET: //
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [EnableCors("MyDomain")]
        [HttpPost]
        public async Task Login(User userFromFore)
        {
            var userFromStorage = TestUserStorage.UserList
                .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);

            if (userFromStorage != null)
            {
                //you can add all of ClaimTypes in this collection 
                var claims = new List()
                {
                    new Claim(ClaimTypes.Name,userFromStorage.UserName) 
                    //,new Claim(ClaimTypes.Email,"[email protected]")  
                };

                //init the identity instances 
                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));

                //signin 
                await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewBag.ErrMsg = "UserName or Password is invalid";

                return View();
            }
        }

        public async Task Logout()
        {
            await HttpContext.Authentication.SignOutAsync("Cookie");

            return RedirectToAction("Index", "Home");
        }


        public static class TestUserStorage
        {
            public static List UserList { get; set; } = new List() {
                new User { UserName = "peach",Password = "112233"}
            };
        }
    }

HomeController.cs 文件中的两个个请求

        [EnableCors("MyDomain")]
        public IActionResult Index()
        {
            return View();
        }

        // 获取数据测试
        [Authorize]
        [EnableCors("MyDomain")]
        public IActionResult TabData()
        {
            var v = new { Id = 1, Name = "Name" };
            return Json(v);
        }

你可能感兴趣的:(Vue2 axios 携带Cookies跨域请求 后台.net core1.1)