添加到Windows角色自定义角色在ASP.NET MVC 5 [英] Adding custom roles to windows roles in ASP.NET MVC 5

查看:159
本文介绍了添加到Windows角色自定义角色在ASP.NET MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立使用ASP.NET MVC 5的内部网应用。

I'm building an intranet app using ASP.NET MVC 5.

我的目标是有由Active Directory(即我使用的是Windows身份验证)所做的任何用户,则添加组到应用程序(不使用域组)内的任何用户的认证。

My goal is to have the authentication of any user made by the Active Directory (i.e. I'm using the "Windows Authentication"), then add groups to any user inside the application (NOT using domain groups).

我发现一些非常有趣的一件code的位置:

I've found some very interesting piece of code here:

<一个href=\"http://brockallen.com/2013/01/17/adding-custom-roles-to-windows-roles-in-asp-net-using-claims/\" rel=\"nofollow\">http://brockallen.com/2013/01/17/adding-custom-roles-to-windows-roles-in-asp-net-using-claims/

但它不是我的情况下工作:当我装点[授权(角色=AppRole),我不能,即使用户(使用索赔)的授权控制器与AppRole角色相关联

But it's not working in my scenario: when I decorate the controller with [Authorize(Role="AppRole")], I can't be authorized even if the user (using Claims) is associated with the "AppRole" role.

这是我的code:

在Global.asax.cs中

In Global.asax.cs

void Application_PostAuthenticateRequest()
    {
        if (Request.IsAuthenticated)
        {

            string[] roles = Utils.GetRolesForUser(User.Identity.Name);

            var id = ClaimsPrincipal.Current.Identities.First();
            foreach (var role in roles)
            {
                //id.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
                id.AddClaim(new Claim(ClaimTypes.Role, @"Kairos.mil\Compliance"));
            }


            bool pippo = User.IsInRole("Compliance");

            HttpContext.Current.User = (IPrincipal)id ;

            bool pippo2 = User.IsInRole("Compliance");


        }
    }

功能GetRolesForUser如下(和工作正常):

The function GetRolesForUser is as follows (and is working fine):

 public static string[] GetRolesForUser(string username)
    {
        dbOrdiniPersonaliEntities db = new dbOrdiniPersonaliEntities();

        string utente = StripDomain(username);

        string[] gruppi = new string[db.vGruppiUtentis.Where(t => t.KairosLogin == utente).Count()];

        int i=0;

        foreach (var gruppo in db.vGruppiUtentis.Where(t => t.KairosLogin == utente))
        {

            gruppi[i]=gruppo.GruppoDes;
            i=i++;
        }
        return gruppi;
    }

和控制器饰有标准的授权条款:

And the controller is decorated with the "standard" Authorize clause:

[Authorize(Roles="AppRole")]
    public ActionResult Index(string sortOrder, string currentFilter, string DesSearchString,int? page)
    {
      // my code here
    }

任何想法?

在此先感谢

更新

由于@Leandro
我试着如你所说以下code

Thanks @Leandro I've tried as you suggested the following code

void Application_PostAuthenticateRequest()
    {
        if (Request.IsAuthenticated)
        {

            string[] roles = Utils.GetRolesForUser(User.Identity.Name);

            ClaimsIdentity id = ClaimsPrincipal.Current.Identities.First();
            foreach (var role in roles)
            {
                //id.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
                id.AddClaim(new Claim(ClaimTypes.Role, @"Kairos.mil\Compliance"));
            }

            bool pippo = User.IsInRole("Compliance");

            SetPrincipal((IPrincipal)id);

            bool pippo2 = User.IsInRole("Compliance");


        }
    }

但是我收到一个运行时错误时,code到达该点

But I receive a run-time error when the code reaches this point

SetPrincipal((IPrincipal)id);

错误如下:

无法转换类型'System.Security.Principal.WindowsIdentity对象键入'System.Security.Principal.IPrincipal。

感谢您的帮助。

更新2(也许解决)


展望深入SO,我发现这个资源

Hi Looking deeper into SO, I've found this resource

<一个href=\"http://stackoverflow.com/questions/6043100/asp-net-mvc-and-windows-authentication-with-custom-roles?rq=1\">ASP.NET MVC和Windows身份验证与自定义角色

继@Xhalent的答案,我修改了code如下:

Following the answer of @Xhalent, I modified my code as follows

protected void Application_PostAuthenticateRequest()
    {
        if (Request.IsAuthenticated)
        {
            String[] roles = Utils.GetRolesForUser(User.Identity.Name);

            GenericPrincipal principal = new GenericPrincipal(User.Identity, roles);

            Thread.CurrentPrincipal = HttpContext.Current.User = principal;
        }
    }

现在看来工作的罚款!任何意见?什么缺点?非常感谢!

It seems now working fine! Any comments? Any drawbacks? Thanks a lot!!

推荐答案

使用这个方法来保存本金,所以它也建立在跟帖:

Use this method to save the principal, so it sets up also in the thread:

     private void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }

更新:也允许匿名和测试,如果User.IsInRole越来越方法内在的东西。

Update: Also allow anonymous and test if User.IsInRole is getting something inside the method.

这篇关于添加到Windows角色自定义角色在ASP.NET MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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