سؤال

I have an application in MVC 4, ASP.NET 4.5 and Windows Authentication. I'm trying to extend the Identity and Principal objects (WindowsIdentity and WindowsPrincipal respectively) in order to provide additional information about the user logged on, but when I try to create the extended instance of these objects and replace the Current.User it throws an error:

System.UnauthorizedAccessException: "Attempted to perform an unauthorized operation." 

Below the code I'm using in the 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;
        }
    }

Here is the web.config settings:

<authentication mode="Windows" >
</authentication>
<authorization>
    <deny users="?" />
</authorization>

And in my local IIS I have set the authentication this way:

  • Anonymous: Disabled
  • Basic: Disabled
  • Windows Authentication: Enabled
  • Forms Authentication: Disabled
  • ASP.NET Impersonation: Disabled
هل كانت مفيدة؟

المحلول

The solution for my problem was given in this question: MVC3 Windows Authentication override User.Identity, in the edit that the user made on its own question.

Basically, to summarize it: I was doing the replace of the Principal in the event public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticateEventArgs args), and I was supposed to do it in protected void Application_AuthorizeRequest(object sender, EventArgs e) (which is not the same as in Forms Authentication Application_AuthenticateRequest).

The code in Global.asax ends up being something like this:

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;
        }
    }

From here, the User is replaced with the extended version of the Principal and the rest of the application can consume it from anywhere (view, controller, etc).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top