小编And*_*eri的帖子

在ASP.NET MVC 5中向Windows角色添加自定义角色

我正在使用ASP.NET MVC 5构建一个Intranet应用程序.

我的目标是对Active Directory所做的任何用户进行身份验证(即我使用"Windows身份验证"),然后将组添加到应用程序内的任何用户(不使用域组).

我在这里找到了一些非常有趣的代码:

http://brockallen.com/2013/01/17/adding-custom-roles-to-windows-roles-in-asp-net-using-claims/

但它在我的场景中不起作用:当我使用[Authorize(Role ="AppRole")]装饰控制器时,即使用户(使用声明)与"AppRole"角色相关联,我也无法获得授权.

这是我的代码:

在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");


        }
    }
Run Code Online (Sandbox Code Playgroud)

函数GetRolesForUser如下(并且工作正常):

 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 …
Run Code Online (Sandbox Code Playgroud)

asp.net windows-authentication asp.net-mvc-5

6
推荐指数
1
解决办法
2973
查看次数