Vue2 axios 攜帶Cookies跨域請求
- 后臺 .net core v1.1
- axios v0.16.2
- 前端框架Vue 2.3.3
前端代碼 axios
- 設(shè)置 withCredentials: true
- 就是要在原來的請求中設(shè)置這個屬性為true就可以
// 需要驗證的才能請求的數(shù)據(jù)
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()
})
后臺代碼
-
需要安裝兩個包
- <PackageReference Include="microsoft.aspnetcore.authentication.cookies" Version="1.1.2" />
- <PackageReference Include="Microsoft.AspNetCore.Cors" Version="1.1.2" />
跨域的參考 不記得是哪一篇下次補上
配置這些只要在需要的 Controller 請求添加 [EnableCors("MyDomain")]允許跨域注釋 [Authorize] 需要登錄驗證注釋
-
需要注意的是我在測試過程中 Home/index 一定要加允許跨域注釋,不然提示受控制訪問不了登陸請求(可能是我的配置不對)
Startup.cs文件配置
public void ConfigureServices(IServiceCollection services)
{
// 跨域請求設(shè)置
var urls = "http://localhost:/"; // 還沒有研究這個什么我設(shè)置的是我的訪問路徑
services.AddCors(options =>
options.AddPolicy("MyDomain",
builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
// mvc設(shè)置
services.AddMvc();
// 身份驗證
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// 身份驗證
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Login"),// 登陸路徑 , 如果沒有登陸跳轉(zhuǎn)到的登陸路徑
AccessDeniedPath = new PathString("/Account/Forbidden"), //禁止訪問路徑:當(dāng)用戶試圖訪問資源時,但未通過該資源的任何授權(quán)策略,請求將被重定向到這個相對路徑。
AutomaticAuthenticate = true, //自動認(rèn)證:這個標(biāo)志表明中間件應(yīng)該會在每個請求上進(jìn)行驗證和重建他創(chuàng)建的序列化主體。
AutomaticChallenge = true, //自動挑戰(zhàn):這個標(biāo)志標(biāo)明當(dāng)中間件認(rèn)證失敗時應(yīng)該重定向瀏覽器到登錄路徑或者禁止訪問路徑。
SlidingExpiration = true, //Cookie可以分為永久性的和臨時性的。 臨時性的是指只在當(dāng)前瀏覽器進(jìn)程里有效,瀏覽器一旦關(guān)閉就失效(被瀏覽器刪除)。 永久性的是指Cookie指定了一個過期時間,在這個時間到達(dá)之前,此cookie一直有效(瀏覽器一直記錄著此cookie的存在)。 slidingExpriation的作用是,指示瀏覽器把cookie作為永久性cookie存儲,但是會自動更改過期時間,以使用戶不會在登錄后并一直活動,但是一段時間后卻自動注銷。也就是說,你10點登錄了,服務(wù)器端設(shè)置的TimeOut為30分鐘,如果slidingExpriation為false,那么10:30以后,你就必須重新登錄。如果為true的話,你10:16分時打開了一個新頁面,服務(wù)器就會通知瀏覽器,把過期時間修改為10:46。 更詳細(xì)的說明還是參考MSDN的文檔。
});
}
AccountController.cs 文件
public class AccountController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[EnableCors("MyDomain")]
[HttpPost]
public async Task<IActionResult> 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<Claim>()
{
new Claim(ClaimTypes.Name,userFromStorage.UserName)
//,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")
};
//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<IActionResult> Logout()
{
await HttpContext.Authentication.SignOutAsync("Cookie");
return RedirectToAction("Index", "Home");
}
public static class TestUserStorage
{
public static List<User> UserList { get; set; } = new List<User>() {
new User { UserName = "peach",Password = "112233"}
};
}
}
HomeController.cs 文件中的兩個個請求
[EnableCors("MyDomain")]
public IActionResult Index()
{
return View();
}
// 獲取數(shù)據(jù)測試
[Authorize]
[EnableCors("MyDomain")]
public IActionResult TabData()
{
var v = new { Id = 1, Name = "Name" };
return Json(v);
}