我正在使用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"); } }
函数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 (var gruppo in db.vGruppiUtentis.Where(t => t.Kairoslogin == utente)) { gruppi[i]=gruppo.Gruppodes; i=i++; } return gruppi; }
控制器使用“标准”Authorize子句进行修饰:
[Authorize(Roles="AppRole")] public ActionResult Index(string sortOrder,string currentFilter,string DesSearchString,int? page) { // my code here }
任何的想法?
提前致谢
UPDATE
谢谢@Leandro
我试过你提出以下代码
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,@"Kairos.mil\Compliance")); } bool pippo = User.IsInRole("Compliance"); SetPrincipal((IPrincipal)id); bool pippo2 = User.IsInRole("Compliance"); } }
SetPrincipal((IPrincipal)id);
错误如下
无法将类型为“System.Security.Principal.WindowsIdentity”的对象强制转换为“System.Security.Principal.IPrincipal”.
谢谢你的帮助
更新2(可能已解决)
你好
深入了解SO,我找到了这个资源
ASP.NET MVC and Windows Authentication with custom roles
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; } }
看来现在工作正常!任何意见?有什么缺点吗?非常感谢!!