User.IsInRole在ASP.NET Core中没有返回任何内容(已实现存储库模式)

我有一个ASP.NET Core(完整.NET Framework)应用程序,具有以下配置:

Startup.cs

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity(p => { p.Password.RequireDigit = true; p.Password.RequireNonAlphanumeric = false; p.Password.RequireUppercase = true; p.Password.RequiredLength = 5; }) .AddEntityFrameworkStores() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); } 

ApplicationUser从IdentityUser扩展而ApplicationDbContext扩展IdentityDbContext

 public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() : base() { } public ApplicationDbContext(DbContextOptions options) : base(options) { } public virtual void Commit() { base.SaveChanges(); } protected override void OnConfiguring(DbContextOptionsBuilder builder) { base.OnConfiguring(builder); builder.UseSqlServer("connection string here"); } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); // Configure model // Identity new Configuration.Identity.ApplicationUserConfiguration(builder.Entity()); new Configuration.Identity.ApplicationUserProfileConfiguration(builder.Entity()); new Configuration.Identity.RoleConfiguration(builder.Entity()); new Configuration.Identity.RoleClaimConfiguration(builder.Entity<IdentityRoleClaim>()); new Configuration.Identity.ApplicationUserRoleConfiguration(builder.Entity<IdentityUserRole>()); new Configuration.Identity.ApplicationUserClaimConfiguration(builder.Entity<IdentityUserClaim>()); new Configuration.Identity.ApplicationUserLoginConfiguration(builder.Entity<IdentityUserLogin>()); new Configuration.Identity.ApplicationUserTokenConfiguration(builder.Entity<IdentityUserToken>()); } } 

这是我的演示数据:

角色表

角色表

用户表

用户表

UserRole表

UserRole表

在我的登录操作中,我有以下内容:

 [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { if (User.IsInRole("Admin")) { return RedirectToAction("Index", "Home", new { area = "Admin" }); } return RedirectToAction("Index", "Home"); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } 

我想要实现的是在登录后将用户重定向到某个区域。

我面临的当前问题是函数User.IsInRole("Admin")返回false并且在调试模式下,如果我查看usermanager,则当前用户没有加载角色(Count = 0)。

任何想法将不胜感激。

更新1

忽略角色ID原因是错误的。 实际上,用户使用正确的值进行映射。

User.IsInRole正在检查cookie。 但是您在登录时在同一个http请求中检查此内容。 Cookie根本就不存在 – 它将在回复或下一个请求中提供。

此时,您需要使用ApplicationUserManager.IsInRoleAsync(TKey userId, string role)来检查数据库。

经过几个小时的搜索,我在使用Azure Active Directory和Roles时意识到ASP.Net Core的这项工作

  User.HasClaim(ClaimTypes.Role,"admin"); 

这不

  User.IsInRole("admin"); 

我也发现了与Kaptain Babbalas相同的问题,并发现在OnTokenValidated中手动重新添加角色会使User.Claims的结果翻倍,但会导致User.IsInRole运行

 options.Events = new OpenIdConnectEvents { OnTokenValidated = (context) => { var claims = new List(); foreach (var claim in context.Principal.Claims) { if (claim.Type == ClaimTypes.Role) claims.Add(new Claim(ClaimTypes.Role, claim.Value)); } var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); context.Principal.AddIdentity(claimsIdentity); return Task.CompletedTask; } };