我将Asp.Net Core 2.1 Identity添加到了项目中。我能够成功注册用户并使用脚手架视图进行身份验证。
register.cs中有一些代码,可以自动将注册帐户分配给角色“ TestRole”,并在数据库中验证该角色已与测试帐户相关联。
userManager.AddToRoleAsync(user, "TestRole").Wait();
当我添加[Authorize]
属性route属性时,会得到预期的行为,或者如果用户未登录,则将其定向到登录屏幕。但是,当我使用[Authorize(Roles ="TestRole")]
属性时,将被拒绝访问尽管已通过身份验证的帐户已与“ TestRole”相关联,但该页面仍显示在页面上
类似的SO QA(https://stackoverflow.com/a/46890346/1843966)在启动时验证了app.usemvc
的顺序得到了一个流行的答案,但我已经确认自己做得很好。
当帐户与指定角色相关联时,什么会导致拒绝该请求?
StartUp.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var context = services.AddDbContextPool<myAppContext>( // replace "YourDbContext" with the class name of your DbContext
options => options.UseMySQL("server=x.x.x.x;port=x;user=xyz;database=xyz;password=xyz"));
services.AddDefaultIdentity<myAppUser>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<myAppContext>();
services.AddAuthentication();
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider service)
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
dotnet控制台日志:
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ForbidResult[1]
Executing ForbidResult with authentication schemes ().
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[13]
AuthenticationScheme: Identity.Application was forbidden.