1

I can find out whether the current user is in a particular role by using the following method:

HttpContext.Current.User.IsInRole("Administrator");

But how does HttpContext know which roles the user is in? Is it stored in a cookie? If so, how does that cookie get created?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
William
  • 3,335
  • 9
  • 42
  • 74
  • 1
    Have you been through one of the Microsoft tutorials? Here is the security section of one: http://www.asp.net/mvc/tutorials/older-versions/nerddinner/secure-applications-using-authentication-and-authorization – Ramoth Mar 21 '14 at 00:05
  • 1
    `HttpContext` doesn't know about the roles of the user. It has a property named `User` which is of type [`IPrincipal`](http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx). `IPrincipal` has an `IsInRole` method. – John Saunders Mar 21 '14 at 00:16
  • okay, well how does IPrincipal know about it? – William Mar 21 '14 at 00:25

1 Answers1

2

It depends from the implementation of IPrincipal interface that stored in HttpContext.Current.User. If you use SqlMembership or Universal membership provider I believe that when you call IsInRole("Administrator") it will hit your database. You can check it with SQL profiler for sure.

By the way you can set to HttpContext.Current.User property your own implementation in Application_PostAuthenticateRequest method. Look here for more information.

UPDATE: Let me clearify my answer. By default asp.net grabs your role provider that goes with membership provider. So the first option to override IsInRole behavior is to write your own role provider (Look here for more information).

Another option would be to write your own implementation of IPrincipal like this:

public class CustomPrincipal : IPrincipal
{
    public IIdentity Identity { get; private set; }
    public bool IsInRole(string role) { 
        //Here goes your implementation of IsInRole
    }
}

and hook it in Global.asax Application_PostAuthenticateRequest method:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    //here you need to check is user authenticated, also you have opportunity to work with authentication ticket

    HttpContext.Current.User = new CustomPrincipal();

}
Community
  • 1
  • 1
Oleksii Aza
  • 5,368
  • 28
  • 35
  • so then do the roles get stored on the client machine at all? Or does it rely on the database? – William Mar 21 '14 at 00:26
  • 1
    I think by default in SqlMembership and Universal membership providers role check always occurs on the database. But you can write your own implementation of IPrincipal and store roles wherever you want including client machine. – Oleksii Aza Mar 21 '14 at 00:31
  • Okay, but if I create an object called 'WilliamsHappyClassRole' and use it as the role class in my program, how does SqlMembership know to use that one in particular? – William Mar 21 '14 at 00:47