【发布时间】:2015-07-16 21:38:04
【问题描述】:
我正在使用 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")] 装饰控制器时,即使用户(使用 Claims)与“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(Roles="AppRole")]
public ActionResult Index(string sortOrder, string currentFilter, string DesSearchString,int? page)
{
// my code here
}
有什么想法吗?
提前致谢
更新
感谢@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, role.ToString()));
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
按照@Xhalent的回答,我修改了我的代码如下
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;
}
}
现在看来工作正常!有cmets吗?有什么缺点吗?非常感谢!!
【问题讨论】:
-
这行得通。我很高兴找到这个。只是可以改进一点的东西。而不是在 Application_PostAuthenticateRequest 中设置 Principle,而是使用链接 forums.asp.net/t/… 中提到的 Application_AuthenticateRequest。请使用带有条件 HttpContext.Current.User != null 的 if 中的代码,因为在设置 User 之前和设置 User 之后都会调用此方法。
标签: asp.net asp.net-mvc-5 windows-authentication