我正在研究 asp.net 应用程序。我有 4 个角色的 aspnetroles 表:
**Id Name**
1 Admin
4 Consumer
2 Provider
3 SaleUser
Run Code Online (Sandbox Code Playgroud)
在 AccountController Register Action 方法中,我添加了这个:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email};
var result = await UserManager.CreateAsync(user, model.Password);
**UserManager.AddToRole(user.Id, model.UserRole);**
Run Code Online (Sandbox Code Playgroud)
现在我在登录时检查登录操作结果如下:
我看到 aspnetusers 和 aspnetuseroles 表有正确的数据。
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
if (User.IsInRole(model.UserRole))
return RedirectToLocal(returnUrl);
Run Code Online (Sandbox Code Playgroud)
但条件失败。如何检查用户是否属于特定角色。
我在 Startup.cs ConfigureAuth 方法中添加了以下行:
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
Run Code Online (Sandbox Code Playgroud)
和 identityConfig 类中的这个类:
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
return new ApplicationRoleManager(roleStore);
}
}
Run Code Online (Sandbox Code Playgroud)
和 accountcontroller 中的这段代码:
private ApplicationRoleManager roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return this.roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set { this.roleManager = value; }
}
Run Code Online (Sandbox Code Playgroud)
但还是同样的问题
更新
var user = new ClaimsPrincipal(AuthenticationManager.AuthenticationResponseGrant.Identity);
if (User.IsInRole(model.UserRole))
return RedirectToLocal(returnUrl);
else
{
AuthenticationManager.AuthenticationResponseGrant = null;
model.Roles = GetRoles();
ModelState.AddModelError("", "You cannot login as " + model.UserRole);
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
请试试这个
if (result == SignInStatus.Success)
{
var user = new ClaimsPrincipal(AuthenticationManager.AuthenticationResponseGrant.Identity);
if (user.IsInRole(model.UserRole))
{
return RedirectToLocal(returnUrl);
}
else
{
AuthenticationManager.AuthenticationResponseGrant = null;
model.Roles = GetRoles();
ModelState.AddModelError("", "You cannot login as " + model.UserRole);
return View(model);
}
}
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
Run Code Online (Sandbox Code Playgroud)
问题是它User是根据您发送到浏览器的 cookie 创建的,但此时您还没有发送它们。
| 归档时间: |
|
| 查看次数: |
4583 次 |
| 最近记录: |