授权(角色="管理员")导致MVC5身份2中的无限循环

时间:2016-02-29 08:30:14

标签: asp.net-mvc asp.net-identity

我们有一个MVC 5 Identity 2项目。如何限制对管理员的控制器访问?当Admin用户访问下面的控制器时,系统会提示他们登录,但是通过CTOR会有无限循环

[Authorize(Roles = "Admins")]
public class AdminController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    public AdminController()
    {
    }
    public AdminController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set
        {
            _signInManager = value;
        }
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

但是,如果我将[Authorize(Roles = "Admins")]更改为[Authorize],则可以正常使用。如何将对此控制器的访问权限限制为管理员?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案here

我没有意识到RoleManager默认情况下没有启动。要ConfigureAuth我添加了这一行app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

IdentityConfig.cs我添加了

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

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<CustomersContext>()));

        return appRoleManager;
    }
}

然后将RoleManager注入AdminController

的构造函数中
private ApplicationRoleManager _roleManager;
public AdminController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,
ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }

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

并且所有都是嘀嗒声嘘声