扩展WindowsIdentity / WindowsPrincipal

时间:2014-04-09 14:29:37

标签: asp.net-mvc-4 windows-authentication asp.net-4.5 windows-identity windows-principal

我在MVC 4,ASP.NET 4.5和Windows身份验证中有一个应用程序。我试图扩展Identity和Principal对象(分别是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中,我以这种方式设置了身份验证:

  • 匿名:已禁用
  • 基本:已禁用
  • Windows身份验证:已启用
  • 表单身份验证:已禁用
  • ASP.NET模拟:已禁用

1 个答案:

答案 0 :(得分:1)

我的问题的解决方案在这个问题中给出了MVC3 Windows Authentication override User.Identity,在用户根据自己的问题进行的编辑中。

基本上,总结一下:我在public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticateEventArgs args)事件中替换了Principal,而我应该在protected void Application_AuthorizeRequest(object sender, EventArgs e)中执行它(这与Forms Authentication { {1}})。

Global.asax中的代码最终会是这样的:

Application_AuthenticateRequest

从这里开始,用户将替换为Principal的扩展版本,应用程序的其余部分可以从任何地方(视图,控制器等)使用它。