简体   繁体   English

使用自定义身份验证时,ASP.NET MVC分配角色

[英]ASP.NET MVC Assign Roles when using custom authentication

I am using MongoDB to store users and passwords (instead of sql). 我正在使用MongoDB来存储用户和密码(而不是sql)。 I have my own mechanism for assigning roles to users. 我有自己的机制来为用户分配角色。 I would like to decorate my controller actions with roles, as follows: 我想用角色来装饰控制器动作,如下所示:

[Authorize(Roles = "Administrators")]

My login code looks like this: 我的登录代码如下所示:

if (mongo.AuthenticateUser(model.UserName, model.Password))
{
    FormsService.SignIn(model.UserName, model.RememberMe);
}

What is the simplest way for me to 'stamp' a users roles onto the user when they first login (the database will provide me with the role names, I just need to set them within the users context). 对我来说,最简单的方法是在用户首次登录时将用户角色“盖印”到用户上(数据库将为我提供角色名称,我只需要在用户上下文中进行设置即可)。 I guess I'm looking for my code to look something like this: 我想我正在寻找我的代码看起来像这样:

if (mongo.AuthenticateUser(model.UserName, model.Password))
{
    if ((mongo.IsAdmin)
    {
        // How do I grant the admin role???
        SomeSortOfUserContext.Add('Administrators');????????
    }
    FormsService.SignIn(model.UserName, model.RememberMe);
}

Add roles to User Principal in Application_AuthenticateRequest in Global.asax. 将角色添加到Global.asax的Application_AuthenticateRequest中的用户主体。

Check this out; 检查这个出来;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM