Search code examples
asp.netforms-authenticationiprincipaliidentity

Role-based Security without Forms Authentication in ASP .NET


I would like to take advantage of:

        Page.User.IsInRole("CustomRole");
        Page.User.Identity.IsAuthenticated

when working inside Page methods, as well as authorization section in web.config:

<authorization>
    <allow roles="Administrators, Supervisors" />
    <deny users="*" />
</authorization>

and also apply rules on classes and methods level:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] 

In my application I authenticate with ... custom mechanism that provides me user identity in ... http header. I get users PIN number (some kind of ID) + roles. But that is a side plot. It doesn't matter.

What I actually want to achieve is to take advantage of ASP .NET build in Authorization features but having my custom authentication mechanism. I guess I have to implement IPrincipal and IIdentity, is that right? I saw plenty of samples on the web but all of them include web.config configuration that specifies providers, and also FormsAuthentication like classes, that I guess I don't need. I just need to inject my user object (which is prepared by me) into request and that's it.

So:

  • what's the easiest way to achieve it?
  • what is the difference between GenericPrincipal / IPrincipal?
  • how to get/create IIdentity object? I saw samples with:

    var id = new FormsIdentity(authTicket);

but I'm not using FormsAuthentication.

Thanks


Solution

  • In short, you have to implement your own authentication module.

    An authentication module is just an ASP.NET module but having special purpose. Its AuthenticateRequest method should populate HttpContext.Current.User property with an instance of IPrincipal.

    Answering your other questions: IPrincipal is just an interface while GenericPrincipal is one of its implementations. You can use it, as the name suggests it's just a generic implementation which means that it should suit you. Since IPrincipal is just IIdentity plus roles, you probably will also need GenericIdentity.

    Other implementations, like RolePrincipal + FormsIdentity are designed for specific purposes, these two for example are used by the Forms Authentication Module.

    There are some good examples available, just google for "custom authentication module".