本文介绍了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

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("[email protected]");
        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 .

原因是默认情况下不会启用Roles.

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<TUser>()来配置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 .

对于ASP.NET Core 3.1,调用.AddRoles<IdentityRole>():

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身份:基于角色的授权-&gt;拒绝访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:23