authentication and authorizing in ASP.NET MVC 5 authentication and authorizing in ASP.NET MVC 5 asp.net asp.net

authentication and authorizing in ASP.NET MVC 5


You can still customize the AuthorizeAttribute in MVC 5 using ASP.NET Identity. There is an example of doing this in the SimpleSecurity Project. Here is a customized AuthorizedAttribute you can use for controllers and here is customized AuthorizeAttribute you can use for Web API's. The concept behind these custom AuthorizeAttributes is to decouple your security model from your application model which is discussed here. The one for the Web API's also supports basic authentication.

The security pipeline has changed with the introduction of OWIN and I did run into some issues with the behavior of AuthorizeAttribute for Web API's, which is discussed here.

You will also find examples in the SimpleSecurity project on porting of the old membership provider called SimpleMembership to MVC 5. Some of the issues with the upgrade process are discussed here. I did get it to work though so you could go with the old membership provider implementation. But my recommendation would be to go with the ASP.NET Identity as this is the way going forward that Microsoft will be supporting, it is a more flexible architecture, and it eliminates many of the issues found in the old membership provider implementations.


Ben Foster has a two-part series that takes you through steps on implementing cookie-based authentication with ASP.NET Identity from the ground up, starting off with a new Web app with no authentication selected. Follow along "ASP.NET Identity Stripped Bare" Part 1 and Part 2.

use the following Authorize attribute to handle unauthorized access when the user is already authenticated.

public class LoggedOrAuthorizedAttribute : AuthorizeAttribute {    public LoggedOrAuthorizedAttribute()     {        View = "error";        Master = String.Empty;     }     public String View { get; set; }     public String Master { get; set; } public override void OnAuthorization(AuthorizationContext filterContext) {   base.OnAuthorization(filterContext);   CheckIfUserIsAuthenticated(filterContext); }    private void CheckIfUserIsAuthenticated(AuthorizationContext filterContext) {    // If Result is null, we’re OK: the user is authenticated and authorized.    if (filterContext.Result == null)       return;    // If here, you’re getting an HTTP 401 status code. In particular,   // filterContext.Result is of HttpUnauthorizedResult type. Check Ajax      here.    if (filterContext.HttpContext.User.Identity.IsAuthenticated)     {       if (String.IsNullOrEmpty(View))          return;       var result = new ViewResult {ViewName = View, MasterName = Master};       filterContext.Result = result;    }  }}