我有一个在MVC 4,ASP.NET 4.5和中的应用程序。我试图扩展标识对象和主体对象(分别为WindowsIdentity和WindowsPrincipal ),以便提供有关登录用户的其他信息,但是当我试图创建这些对象的扩展实例并替换Current.User时,它会引发一个错误:
System.UnauthorizedAccessException: "Attempted to perform an unauthorized operation." 下面是我在global.asax中使用的代码:
public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)
{
if (!args.Identity.IsAnonymous)
{
var userData = WindowsUserDataHelper.GetWindowsUserData(args.Identity);
var user = new MyCustomPrincipal(new MyCustomIdentity(args.Identity.Name, userData));
HttpContext.Current.User = user; //-- exception thrown here
Thread.CurrentPrincipal = user;
}
}以下是web.config设置:
<authentication mode="Windows" >
</authentication>
<authorization>
<deny users="?" />
</authorization>在本地IIS中,我以这样的方式设置了身份验证:
发布于 2014-04-11 22:14:50
我的问题的解决方案是在这个问题中给出的:MVC3 Windows Authentication override User.Identity,在用户根据自己的问题进行的编辑中。
简单地说,我是在事件public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticateEventArgs args)中替换主体,而我应该在protected void Application_AuthorizeRequest(object sender, EventArgs e) (这与表单身份验证Application_AuthenticateRequest中不一样)中进行替换。
Global.asax中的代码最后如下所示:
protected void Application_AuthorizeRequest(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
var userData = WindowsUserDataHelper.GetWindowsUserData((WindowsIdentity)User.Identity);
var user = new MyCustomPrincipal(new MyCustomIdentity(User.Identity.Name, userData));
HttpContext.Current.User = user;
Thread.CurrentPrincipal = user;
}
}从这里开始,用户将被主体的扩展版本所取代,应用程序的其余部分可以在任何地方(视图、控制器等)使用它。
https://stackoverflow.com/questions/22965731
复制相似问题