views:

901

answers:

2

Is there any good way of combining ASP.NET Windows Authentication with a custom IPrincipal/IIdentity object? I need to store the user's email address and have done so for Forms Authentication using a custom IIdentity/IPrincipal pair that I added to the Context.CurrentUser during the AuthenticateRequest event.

How would I best go by to accomplish this using WindowsAuthentication?

+1  A: 

Maybe you could create your "ExtendedWindowsPrincipal" as a derived class based on WindowsPrincipal, and just add your extra data to the derived class?

That way, your ExtendedWindowsPrincipal would still be recognized anywhere where a WindowsPricinpal is needed.

OR: since you're talking about using Windows Authentication, you're probably in a Windows network - is there an Active Directory or a user database somewhere, where you could look up your e-mail address that you're interested in instead of storing it in the principal?

Marc

marc_s
Creating a derived class was my idea, but I'm unsure on if it's wise to replace the IPrincipal and how it's done correctly.I intent to lookup the email address from the directory, but my idea was to collect all user information in one place, just like I have done w. custom authentication.
PHeiberg
I don't see any problem replacing a WindowsPrincipal by your own ExtendedWindowsPrincipal, if it's a derived class. After all, it's still a WindowsPrincipal - with some added stuff.To do it, I would investigate the global.asax and the Application_AuthenticateRequest.
marc_s
I got problems with trying to get the IsInRole to still work and didn't want to invest the time into using IPrincipal, so I ended up putting the rest of the user information in the context items. Thanks for the help.
PHeiberg
A: 

I ended up refactoring my initial solution into replacing the Principal instead of the Identity as I originally thought. Replacing the Identity proved troublesome, since i ran into security problems when creating an instance of a new extended WindowsPrincipal.

public class ExtendedWindowsPrincipal : WindowsPrincipal
{
    private readonly string _email;

    public ExtendedWindowsPrincipal(WindowsIdentity ntIdentity, 
       string email) : base(ntIdentity)
    {
            _email = email;
    }

    public string Email
    {
        get { return _email; }
    }
}

In my Authentication module i replaced the principal on the HttpContext like this:

var currentUser = (WindowsIdentity)HttpContext.Current.User.Identity;
HttpContext.Current.User = 
    new ExtendedWindowsPrincipal(currentUser, userEmail);
PHeiberg