Can I just use Session["role"] = "theRole", or that would be a bad practice, so I would create my custom authorize attribute where I'm going to look into the Session
It is not bad, but the good principle is to use the Principal object and using the membership provider to answer your queries for Roles.
Generally anytime you're rolling your own security, it's questionable at best. Is there some reason you can't use the built-in User object and IsInRole method to make your determination?
Or if you have custom security roles you can build you own classes holding all the information you need then after login save the whole class to the session to save querying the dabase everytime you need the information
Custom authorize attribute is better as it is easily to inject on actions and also there is one place where your authentication/authorization logic resides.
Instead of creating a new Session variable, how about using the existing HttpContext.Current.User? That is in the System.Security.Principal namespace.
It has an array of roles which you can populate, and then test against by using if (thisUser.IsInRole("admin"))
...
Just for illustration purposes, here is one way to populate the roles in a manually-authenticated User. In most situations, you will already have the authenticated user.
System.Web.Security.FormsIdentity id = new FormsIdentity(new FormsAuthenticationTicket("dok", false, 30));
string[] roles = { "admin" };
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
I would advise against it. .Net already has plenty of built in functionality to implement security features. Don't re-invent the wheel, especially where security is concerned.
You do not need to implement a membership provider. All you need to do is set HttpContext.User
to a custom IPrincipal and you can use User.IsInRole("role")
and [AuthorizeAttribute(Roles="role")]
.
I would suggest role information is more suited to the authorization ticket than the session. Storing the data in the session could cause added problems of syncing the session lifespan with the authorization ticket lifespan. The session could possibly expire while the user is still logged in.