我正在使用角度为6的Web API内核 为了进行身份验证,我将身份与服务器cookie一起使用 一切正常,但是当我想使用 [Authorize] 属性时 具有或不具有任何作用的角色,它始终会作为未经授权的请求返回401。
在Startup.ConfigureServices中:
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequiredLength = 8;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireDigit = true;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.DefaultLockoutTimeSpan =
TimeSpan.FromMinutes(Convert.ToInt32(_config["Tokens:accessFailedwaitingMin"]));
options.Lockout.MaxFailedAccessAttempts = Convert.ToInt32(_config["Tokens:accessFailedCount"]);
options.Lockout.AllowedForNewUsers = true;
}).AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
// Override the default events
options.Events = new CookieAuthenticationEvents
{
OnRedirectToAccessDenied = ReplaceRedirectorWithStatusCode(HttpStatusCode.Forbidden),
OnRedirectToLogin = ReplaceRedirectorWithStatusCode(HttpStatusCode.Unauthorized)
};
// Configure our application cookie
options.Cookie.Name = ".test";
options.Cookie.HttpOnly = true; // This must be true to prevent XSS
//options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.None; // Should ideally be "Always"
options.SlidingExpiration = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
然后在 Startup.Configure
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseCookiePolicy();
//app.UseHttpsRedirection();
app.UseMvc();