Posts

Showing posts from December, 2013

Using Claims in ASP.NET Identity

Claims can simplify and increase the performance of authentication and authorization processes. I wrote about how you can use the roles stored as claims to eliminate back-end queries every time authorization takes place .  ASP.NET Identity has good support for claims-based identity and it creates several claims for you automatically when you create a new identity.  Here is how we create the identity for a new user during the log-in process UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext())); ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); If you inspect the Claims property of ClaimsIdentity after calling CreateIdentity you will see that there are there are three or more claims. There is a claim for the user ID, user name, identity provider and one for each role assigned. So what if you want to add some more claims? Here is an ex

Returning 401 HTTP Status Code on Authentication Failure in MVC 5 Web API's

The behavior of how a Web API responds to authentication/authorization exceptions has significantly changed in MVC 5. First, a little background. In a previous article I demonstrated how to create a custom AuthorizeAttribute that mixes basic authentication with forms authentication  when using Web API's.   This custom attribute was designed to return an HTTP status code of 401 (Unauthorized) if authentication failed and a 403 (Forbidden) if the user is not authorized.  The example code was written as part of the SimpleSecurity Project , which was originally written to decouple and enhance the ASP.NET membership provider SimpleMembership.  I recently ported this code to work with the new ASP.NET Identity which replaces SimpleMembership in MVC 5.  It turns out that during my testing of the port I did not do a good job of testing error conditions. Bad tester. The security pipeline in OWIN and MVC 5 has changed and the custom attribute was no longer returning 401 and 403 status cod