使用身份登录时如何验证用户的角色

时间:2019-07-14 16:14:13

标签: c# asp.net asp.net-core asp.net-identity

早上好,全体成员,向大家致以问候。

当用户使用身份登录时,如何验证用户的角色? 第一步寄存器 第二步,登录,但是当我尝试访问具有“管理员”权限的视图时,显示“拒绝访问。您无权访问此资源”。 我希望每个注册用户都具有管理员角色。

我在做什么错了?

[Authorize(Roles = "Admin")]
public IActionResult About()
{
    ViewData["Message"] = "Your application description page.";

    return View();
}
//DBContext
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace test.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
            modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "User", NormalizedName = "User".ToUpper() });
            base.OnModelCreating(modelBuilder);
        }
        public DbSet<Test> Test { get; set; }
    }
}




//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    //DataBase Connection
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    // Library Identity
    services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
    // IdentityOptions
    services.Configure<IdentityOptions>(options =>
    {
        // Default SignIn settings.
        options.SignIn.RequireConfirmedEmail = false;
        options.SignIn.RequireConfirmedPhoneNumber = false;
        // Password settings.
        options.Password.RequireDigit = false;
        options.Password.RequireLowercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequiredLength = 4;
        options.Password.RequiredUniqueChars = 0;

        // Lockout settings.
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        // User settings.
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = false; // ojo con esto
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication(); //  Use Authentication
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
// Register.cs
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
        var result = await _userManager.CreateAsync(user, Input.Password);
        if (result.Succeeded)
        {
            var UserRole = "Admin"; // Admin Role
            var x = await _userManager.AddToRoleAsync(user, UserRole); // Assignment of the role to the registered user
            _logger.LogInformation("User created a new account with password.");
        }
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }
    // If we got this far, something failed, redisplay form
    return Page();
}

1 个答案:

答案 0 :(得分:0)

这是2.1版本中的一个已知错误。参见issue

我遵循using the old api suggested by HaoK and C-BERBER的建议,现在它可以正常工作了。

使用旧式api配置身份:

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