[英]How to create a claim based authorisation system implemented using role names? ASP.NET Core 2.1
[英]ASP.NET Core 2.1: Razor Pages - role based authorisation not working
我的 Razor Pages 应用程序配置如下。 Startup.cs 包含:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy =>
policy.RequireAuthenticatedUser().RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/About", "RequireAdminRole");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
我有一个具有“管理员”角色的用户。 当用户登录并访问“关于”页面时,我得到以下信息:
拒绝访问
您无权访问此资源。
我究竟做错了什么?
更新
如果我删除AuthorizePage
和使用GetUsersInRoleAsync("Admin")
在About.cshtml.cs
页面OnGet
方法,然后输出UserName
在属性About.cshtml
页,显示管理员用户。 所以,不确定为什么AuthorizePage
不起作用。
2017 年 5 月 29 日更新
我的源代码在这个Github 资源库中
我设法找到了解决方案:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
我认为它的工作原理如下:
你必须把.UseAuthentication()
之前.UseMvc()
app.UseAuthentication(); app.UseMvc();
app.UseAuthentication(); app.UseMvc();
因为这个,我掉了很多头发。
请更改这些代码行,然后重试。 谢谢
//Old
/*services
.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
*/
//New
services
.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
上述答案对我不起作用,但在Github上阅读本文后,我更改了使用 Alan T 解决方案的代码。
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
对此
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AuthenticationContext>()
.AddDefaultUI();
.AddEntityFrameworkStores<AuthenticationContext>()
需要跟在services.AddIdentity<IdentityUser, IdentityRole>()
它完美地工作。 我没有使用双因素身份验证,所以我不需要.AddDefaultTokenProviders()
希望它会帮助其他与我在角色上遇到相同问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.