ASP.NET Core 2.1 身份:基于角色的授权

编程入门 行业动态 更新时间:2024-10-25 23:31:33
本文介绍了ASP.NET Core 2.1 身份:基于角色的授权 ->拒绝访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将 ASP.NET Core 2.1 与来自 .NET 的新 Identity 框架结合使用.只要没有请求特定于角色的角色,常规 Authorization 属性就会起作用.

I'm using ASP.NET Core 2.1 with the new Identity framwork from .NET. The regular Authorization attribute works as long as no role specific role is requested.

我是否需要一些扩展/自定义策略来使用角色?以下是我的代码的最小化示例:

Do I need some extending / customized policies to use roles? Below is a minimized sample of my code:

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.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); // Does not change anything // services.AddAuthorization(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

HomeController.cs

HomeController.cs

public async Task<IActionResult> Index() { if (!await _roleManager.RoleExistsAsync("Admin")) { await _roleManager.CreateAsync(new IdentityRole("Admin")); } var user = await _userManager.FindByEmailAsync("danny.meier@tpcag.ch"); if (!await _userManager.IsInRoleAsync(user, "Admin")) { await _userManager.AddToRoleAsync(user, "Admin"); await _userManager.UpdateAsync(user); } return View(); } [Authorize] public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } [Authorize(Roles = "Admin")] public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); }

推荐答案

这是 2.1 版本中的已知问题,已在 2.2 preview-1 中修复.

It's a known issue in the version of 2.1 and has been fixed in 2.2 preview-1 .

原因是AddDefaultIdentity<TUser>() ,在1.NET Core中将引入 ASP 默认启用.

The reason is that the new method of AddDefaultIdentity<TUser>() , which is introduced in ASP.NET Core 2.1 , will not make Roles enabled by default .

要绕过它,而不是使用新的 AddDefaultIdentity() 来配置 Identity ,只需使用旧样式的 api :

To walk around it , instead of using the new AddDefaultIdentity<TUser>() to configure Identity , simply use the old-style api :

services.AddIdentity<AppUser, IdentityRole>() .AddRoleManager<RoleManager<IdentityRole>>() .AddDefaultUI() .AddDefaultTokenProviders() .AddEntityFrameworkStores<ApplicationDbContext>();

另外,如果您之前已经有人登录过,请先退出然后重新登录,现在它会按预期工作.

Also , if you have already signed someone in before , please do logout first and login again , it will work as expected now .

[Edit] 对于 ASP.NET Core 3.1,调用 .AddRoles():

For ASP.NET Core 3.1, invoke .AddRoles<IdentityRole>():

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<AppIdentityDbContext>();

然后注销并重新登录.

更多推荐

ASP.NET Core 2.1 身份:基于角色的授权

本文发布于:2023-11-14 10:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:角色   身份   NET   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!