在身份ASP MVC中查找用户角色 [英] find user role in identity asp mvc

查看:88
本文介绍了在身份ASP MVC中查找用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码进行登录.用户登录后如何找到用户角色?

I am using this code for login. How can I find a user role when user login?

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {

        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = await UserManager.FindByNameAsync(model.Username);
        if (user != null)
        {
            if (!await UserManager.IsEmailConfirmedAsync(user.Id))
            {
                ViewBag.errorMessage = "You must have a confirmed email to log on.";
                return View("Error");
            }
        }
        var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

推荐答案

user.Roles将获取用户所属的角色列表.根据您的要求,您可以执行以下操作

user.Roles will fetch list of Roles user belong to. Based on your requirement you can do something like below

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{

    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var user = await UserManager.FindByNameAsync(model.Username);
    if (user != null)
    {
        if (!await UserManager.IsEmailConfirmedAsync(user.Id))
        {
            ViewBag.errorMessage = "You must have a confirmed email to log on.";
            return View("Error");
        }
    }
    var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            if(await UserManager.IsInRoleAsync(user.Id,"Admin")) //<= Checking Role and redirecting accordingly.
                return RedirectToAction("Index", "Admin");
            else
                return RedirectToAction("Index", "User");
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

根据我们的讨论,如果您想从数据库中获取所有角色,则需要在下面进行

Based on our discussion if you want to fetch all the roles from database you need to do below

如下所示将ApplicationRoleManager类添加到IdentityConfig.cs中

Add ApplicationRoleManager class to your IdentityConfig.cs as below

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return manager;
    } 
}

将RoleManager分配给Owin Context,因此将以下内容添加到starup.auth.cs

Assign RoleManager to Owin Context, so add below to starup.auth.cs

public void ConfigureAuth(IAppBuilder app)
    {
     // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        //other code here
}

在AccountController.cs中添加属性

In AccountController.cs add a property

    private ApplicationRoleManager _roleManager;

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

将其传递给构造函数

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,ApplicationRoleManager roleManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }

完成此操作后,您可以使用来获取所有角色的列表 var role = RoleManager.Roles;

Once you are done with this you can fetch list of all roles by using var roles = RoleManager.Roles;

您可以根据需要使用它.

You can use this as per your requirement.

这篇关于在身份ASP MVC中查找用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆