[英]User.IsInRole returns nothing in ASP.NET Core (Repository Pattern implemented)
我有一个具有以下配置的 ASP.NET Core(完整的 .NET Framework)应用程序:
启动文件
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(p => {
p.Password.RequireDigit = true;
p.Password.RequireNonAlphanumeric = false;
p.Password.RequireUppercase = true;
p.Password.RequiredLength = 5;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IDbFactory, DbFactory>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IUserService, UserService>();
}
ApplicationUser 扩展自 IdentityUser 和 ApplicationDbContext 扩展 IdentityDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> 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<ApplicationUser>());
new Configuration.Identity.ApplicationUserProfileConfiguration(builder.Entity<ApplicationUserProfile>());
new Configuration.Identity.RoleConfiguration(builder.Entity<IdentityRole>());
new Configuration.Identity.RoleClaimConfiguration(builder.Entity<IdentityRoleClaim<string>>());
new Configuration.Identity.ApplicationUserRoleConfiguration(builder.Entity<IdentityUserRole<string>>());
new Configuration.Identity.ApplicationUserClaimConfiguration(builder.Entity<IdentityUserClaim<string>>());
new Configuration.Identity.ApplicationUserLoginConfiguration(builder.Entity<IdentityUserLogin<string>>());
new Configuration.Identity.ApplicationUserTokenConfiguration(builder.Entity<IdentityUserToken<string>>());
}
}
这是我的演示数据:
角色表
用户表
用户角色表
在我的登录操作中,我有以下内容:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> 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 并且在调试模式下,如果我查看用户管理器,当前用户没有加载角色(计数 = 0)。
任何想法将不胜感激。
更新 1
忽略角色 ID 原因是错误的。 事实上,用户被映射到了正确的值。
User.IsInRole
正在检查 cookie。 但是您在登录时在同一个 http 请求中进行检查。 Cookie 尚不存在 - 它将在回复或下一个请求中可用。
此时您需要使用ApplicationUserManager.IsInRoleAsync(TKey userId, string role)
来检查数据库。
如果有人(如我)在 .Net Core 2.1 中为此苦苦挣扎,此链接可能会有所帮助。
简而言之,如果您像这样使用AddDefaultIdentity
:
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
那么角色将无法工作,因为它们没有在 DefaultIdentity 中实现。
对我有用的是将其替换为:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
此外,如果您在上述修复之前登录,请注销并再次登录,以便刷新身份声明。 现在它应该可以工作了。
经过数小时的搜索,我意识到在使用 Azure Active Directory 和角色时可以使用 ASP.Net Core
User.HasClaim(ClaimTypes.Role,"admin");
这不
User.IsInRole("admin");
从 .Net Core 2.1(也适用于 3.1)开始, AddDefaultIdentity
与调用相同:
AddIdentity
AddDefaultUI
AddDefaultTokenProviders
要添加角色功能,请转到ConfigureServices
下的Startup.cs
,您可以像这样使用.AddRoles
:
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>() //<-- This line
.AddEntityFrameworkStores<ApplicationDbContext>();
这就是所需要的。 正如上面提到的那样,注销并重新登录至关重要。
为了记录(并且只是为了测试),我尝试了services.AddIdentity
:
IServiceCollection 不包含“AddIdentity”的定义...
和services.AddIdentityCore
(在调试和显示页面之前没有错误):
InvalidOperationException: 未指定 authenticationScheme,也未找到 DefaultChallengeScheme。 可以使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions) 设置默认方案。
可能还有更多方法可以让后两者正常工作,但我为AddDefaultIdentity
发布的代码是我需要的所有代码,以便让User.IsInRole
和其他角色功能在 .NET Core 2.1 和 3.1 中工作,到目前为止。
我还发现了与 Kaptain Babbalas 相同的问题,并发现在 OnTokenValidated 中手动重新添加角色会使 User.Claims 的结果加倍,但会导致 User.IsInRole 起作用
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = (context) =>
{
var claims = new List<Claim>();
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;
}
};
User.IsInRole()
在SignIn
之后处理下一个 Request 。 在您的代码中, SignIn
和User.IsInRole()
在同一个 Request中执行。 因此,要应用手动重定向,您可以将身份验证代码放在另一个操作中,然后从Login()
操作重定向到该操作,如下所示:
public async Task<IActionResult> 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)
{
return RedirectToAction("ObeyMyOrder");
}
}
public async Task<IActionResult> ObeyMyOrder()
{
if (User.IsInRole("Admin"))
{
return RedirectToAction("Index", "Home", new { area = "Admin" });
}
return RedirectToAction("Index", "Home");
}
现在User.IsInRole()
将起作用。
就我而言,当用户已经登录时,我已将用户添加到数据库中的角色。注销并再次登录解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.