为什么user.Identity.isauthenticated == false通过CORS调用时,但是当通过同一域调用时为true?
我有一个可启用CORS的工作ASP.NET Core 2 Cookieauth应用。
当我打电话时;
api/Identity/stread-session
authcookie在这两个中都被下降了
CORS和本地Ajax致电。
相反,当我打电话
API/IDENTITY/签名
Authcookie被删除。到目前为止一切都很好。
成功建立会议之后,当我致电以下内容时;
api/Identity/check-authentication
用户。我不知道这是因为我在JavaScript中称其为如何称呼,还是在ASP.NET应用程序上配置了错误。我以为我只需要拥有凭证:" inclage"在我的接电话中设置?
[Produces("application/json")]
[Route("api/Identity")]
public class IdentityController : Controller
{
[HttpPost]
[AllowAnonymous]
[Route("establish-session")]
public async Task EstablishAuthenticatedSession(string username, string password)
{
var properties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1)
};
var claims = new[] {new Claim("name", username), new Claim(ClaimTypes.Role, "User")};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
properties);
}
[HttpGet]
[AllowAnonymous]
[Route("sign-out")]
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
[HttpGet]
[AllowAnonymous]
[Route("check-authentication")]
public async Task<bool> CheckAuthentication()
{
return User.Identity.IsAuthenticated;
}
}
这是我的JavaScript片段;
establishAuthenticatedSession(){
let self = this;
var model = this.get();
console.log(model);
var url = "https://localhost:44310/api/Identity/establish-session?username=herb&password=1234";
fetch(url,
{
credentials: 'include',
headers: { 'Content-Type': 'text/plain' },
method: 'POST'
})
.then(function (res) {
console.log(res);
self.set({ establishSession:{ message:"Success" }});
}).catch(function(error) {
self.set({ establishSession:{ message:error.message }});
console.log('There has been a problem with your fetch operation: ' + error.message);
});
},
signOut(){
let self = this;
var model = this.get();
console.log(model);
var url = "https://localhost:44310/api/Identity/sign-out";
fetch(url,
{
credentials: 'include',
headers: { 'Content-Type': 'text/plain' },
method: 'GET'
})
.then(function (res) {
console.log(res);
self.set({ signoutResult:{ message:"Success" }});
}).catch(function(error) {
self.set({ signoutResult:{ message:error.message }});
console.log('There has been a problem with your fetch operation: ' + error.message);
});
},
checkAuthenticatedSession(){
let self = this;
var model = this.get();
console.log(model);
var url = "https://localhost:44310/api/Identity/check-authentication";
fetch(url,
{
credentials: 'include',
method: 'GET',
headers: { 'Content-Type': 'text/plain' }
})
.then(res => res.text())
.then(function (res) {
console.log(res);
self.set({ checkAuthenticatedSession:{ message:res }});
})
.catch(function(error) {
self.set({ checkAuthenticatedSession:{ message:error.message }});
console.log('There has been a problem with your fetch operation: ' + error.message);
});
}
这是我的CORS设置;
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
,因此事实证明,需要将cookie设置为samesitemode.none。我得到的暗示是,从Azure设置为Non的Arafinity Cookie,它是在我的地方发送的。
在我的应用程序中,我必须将其设置为如下;
public class Startup
{
...
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(
CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = "/Account/LogIn"; ;
options.AccessDeniedPath = new PathString("/account/login");
options.Cookie.Name = "AUTHCOOKIE";
options.ExpireTimeSpan = new TimeSpan(365, 0, 0, 0);
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.SameSite = SameSiteMode.None;
}
);
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
var cookiePolicyOptions = new CookiePolicyOptions
{
Secure = CookieSecurePolicy.SameAsRequest,
MinimumSameSitePolicy = SameSiteMode.None
};
app.UseCookiePolicy(cookiePolicyOptions);
...
}
}