简体   繁体   中英

Is it possible to have more than one Principal in ASP.NET?

I was recently given a task to create separate login for users, that belong to certain role. Login was already implemented for main users and this was done with using Principal that was assigned to Thread.CurrentPrincipal and is later checked for value every time a page is loaded. I modified my code to use same mechanism of authentication so in my custom login I create custom Principal and assign it to Thread.CurrentPrincipal . Now the problem with that is that with custom login I override my normal login and vice versa. Is it possible to assign my principle somewhere else than Thread.CurrentPrincipal to allow for both login variants to work at the same time? If this is not possible I would like to learn about alternatives :)

The answer from DVK is valid, but I have had complications in the past when using custom IPrincipal s. An alternative approach is to use a single principal, represented by a ClaimsPrincipal and make use of the fact that it can store multiple identities. You can then use the default implementations of IsInRole for example.

https://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal(v=vs.110).aspx

This is very doable, and not terribly difficult. The best way I've found to do this is to implement a custom IPrincipal that has a property that also contains an IPrincipal. Then you can store both in the thread, and implement the IsInRole method in a manner that allows checking both principal objects for authorization purposes. Some pseudo-code...

public class MyPrincipal : IPrincipal
{
    public IPrincipal FormsPrincipal { get; private set; }

    public MyPrincipal(IPrincipal formsPrincipal)
    {
        FormsPrincipal = formsPrincipal;
    }

    public bool IsInRole(string role)
    {
        if (someCondition)
        {
            // check roles for this
        }
        else
        {
            return FormsPrincipal.IsInRole(role); // check role against the other principal
        }
    }
}

Then on PostAuthenticateRequest, use the current principal to create your new, custom principal, and assign your custom principal as the HttpContext.Current principal.

Good resource with lots of detail: ASP.NET MVC - Set custom IIdentity or IPrincipal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM