I am upgrading a site to use MVC and I am looking for the best way to set up Authentication.
At this point, I have the log-in working off of Active Directory: valida
Could you not drop in either an authorization store role manager or find (e.g. on Codeplex) or write another Role Provider that works with Active Directory to get the groups information?
This would save you the hassle of authenticating the user, getting their roles, and then re-passing that information into the constructor, and would all happen automatically for you as part of the framework.
Roles are added to the IPrincipal of the HttpContext. You can create a GenericPrincipal, parse the list of roles in the constructor and set it as HttpContext.User. The GenericPrincipal will then be accessible through User.IsInRole("role")
or the [Authorize(Roles="role")]
attribute
One way of doing this (in C#) is to add your roles as a comma separated string in the user data parameter when creating your authentication ticket
string roles = "Admin,Member";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userId, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false, //do not remember
roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
Then access the role list from the authentication ticket and create a GenericPrincipal from your Global.asax.cs
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
HttpCookie authCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { ',' });
GenericPrincipal userPrincipal =
new GenericPrincipal(new GenericIdentity(authTicket.Name),roles);
Context.User = userPrincipal;
}
}
For those of you using MVC 4 or Greater you will need to take Jaroslaw Waliszko's advice when making use of David Glenn's answer:
"I've tested it in ASP.NET MVC 4 and I suggest to use Application_PostAuthenticateRequest instead. Otherwise the generic principal will be overridden." – Jaroslaw Waliszko Sep 7 at 16:18
So as stated above, all you need to do is replace the Application_AuthenticateRequest method name with Application_PostAuthenticateRequest to get this to work. Worked like a charm for me! If I was allowed to upvote Jaroslaw and David, I would.
When you authenticate your user, you generate a new GenericPrincipal instance. The constructor takes an array of strings which are the roles for the user. Now set HttpContext.Current.User equal to the generic principal and write the auth cookie, and that should do it.
I'd be inclined to just create a custom role provider. Example here:
http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/