ASP.NET MVC 3 User Authentication / Authorization

I searched all over the Internet and so, and I found some useful materials on this topic, but I have a few questions that I'm still not sure about:

1) I use form authentication with a special authentication provider. Therefore, I use the Authorize attribute and the section in the web.config file, but basically when the FormsAuthenticationTicket does not exist, I am redirected to the login page (specified in the web.config file), which then uses its own authentication provider to authorize the user against db, and then throws FormsAuthenticationTicket . Is it correct?

2) Do I have to use my own Authorize attribute or do I just need to insert the GenericPrincipal into the HttpContext from the Application_AuthenticateRequest event handler on the global.asax page? Or should I use the User.IsInRole insode controller action?

I just need role-based authorization, and I think my authentication scheme is pretty good.

Any pointers / tips?

Thanks Sam

Edit

So, from what I read, the best option for this is to create a custom AuthorizeAttribute and override AuthorizeCore .

So, I did this:

 public class CustomAuthorize : System.Web.Mvc.AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.User.Identity.IsAuthenticated) { var model = AdminUserViewModel.FromJsonString(((FormsIdentity)httpContext.User.Identity).Ticket.UserData); httpContext.User = new GenericPrincipal(HttpContext.Current.User.Identity, model.SecurityGroups.Select(x => x.Name).ToArray()); } return base.AuthorizeCore(httpContext); } protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { //base.HandleUnauthorizedRequest(filterContext); filterContext.Result = new System.Web.Mvc.RedirectResult("/Authentication/NotAuthorized", false); } } 

Just add a new principle / identifier with roles that are stored in the FormsAuthenticationTicket UserData property. Then let the base do the rest.

Does this seem normal?

Edit # 2

I'm a little tired of using Application_AuthenticateRequest in global.asax with IIS7 due to the built-in pipeline, every request fires this event, images, css, js ...

Is it correct?

+7
source share
1 answer

1) I do the same.

2) I use the Authorize attribute and the Application_AuthenticateRequest event handler.

In the Application_AuthenticateRequest event handler, I am doing something like this:

  string[] roles = authenticationTicket.UserData.Split(','); if (Context.User != null) Context.User = new GenericPrincipal(Context.User.Identity, roles); 

And at the controller or action level, I am doing something like this:

  [Authorize(Roles = "Admin, SuperAdmin")] 
+4
source

All Articles