首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MVC - FormsAuthentication获取RoleName

MVC - FormsAuthentication获取RoleName
EN

Stack Overflow用户
提问于 2018-05-30 06:53:54
回答 1查看 96关注 0票数 0

我是ASP.NET MVC的新手,并从本教程link学习如何使用FormAuthentication自定义角色

下面的代码存储了角色。当我在控制器中执行此[Authorize(Roles="admin")]时,它可以正常工作

代码语言:javascript
复制
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;

                using (userDbEntities entities = new userDbEntities())
                {
                    User user = entities.Users.SingleOrDefault(u => u.username == username);

                    roles = user.Roles;
                }
                //let us extract the roles from our own custom cookie


                //Let us set the Pricipal with our user specific details
                HttpContext.Current.User  = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}

有没有办法根据当前的User.Identity获取实际的角色名称?就像下面的伪代码。

代码语言:javascript
复制
[Authorize]    
public ActionResult Index()
{
    bool isAdmin = System.Web.HttpContext.Current.User.IsInRole("admin");  // This also works correctly.
    Response.Write("role: " + isAdmin);

    string roleName = // The Code of How to get the actual Role Name
    Response.Write("roleName: " + roleName);  //e.g Admin, User...

    return View();
}
EN

回答 1

Stack Overflow用户

发布于 2018-05-30 07:16:18

来自评论的

:你知道关于用户名和角色的定制表的OWIN cookie身份验证的好文章吗?

它只有几个部分,所以我在GitHub AspNetMvcActiveDirectoryOwin中创建了一个示例项目。原始源是通过AD进行身份验证,但只需修改查询自定义表的类即可。

以下是主要的三个类:

  1. AccountController
  2. ActiveDirectoryService
  3. OwinAuthenticationService取代FormsAuthentication.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档