Mint forms auth cookie using owin


The old forms authn module has a method that enabled one to mint a ticket and cookie.

In the case of the new Cookie middleware – that plays the same role as forms authn module – we have to do the following – providing a bag of claims (now)

On the login page once the user’s credentials have been validated, we can call into OWIN to authenticate the user. We don’t call the cookie middleware directly, instead we call into the “OWIN Authentication Manager”, which is an abstraction for all of the possible OWIN authentication middleware that’s being used. This call can be seen in the new templates and here’s the code if you wanted to invoke it yourself:

var claims = new List<Claim>();

claims.Add(new Claim(ClaimTypes.Name, "Brock"));

claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));

var id = new ClaimsIdentity(claims,

DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();

var authenticationManager = ctx.Authentication;

authenticationManager.SignIn(id);

The above code creates the set of claims to represent the identity of the user and creates a ClaimsIdentity from the claims. Note the second parameter to the ClaimsIdentity constructor — this indicates the type of authentication. In the OWIN authentication middleware, this authentication type must match that of the middleware being targeted. So since this code is presumably trying to issue a cookie, then this value must be the same as the name we assigned to the cookie middleware from the ConfigureAuth initialization code from above.

Once the ClaimsIdentity is created, we then access the OwinContext which has the AuthenticationManager. We use its SignIn API passing the ClaimsIdentity. This then matches the authentication type to the corresponding authentication middleware and since we match the cookie authentication middleware, a cookie is issued that contains the claims of the ClaimsIdentity.

An additional option on the SignIn API is to pass a AuthenticationProperties object. This has an IsPersistent property that indicates if the cookie is to be persistent.

From http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

Advertisements

About home_pw@msn.com

Computer Programmer who often does network administration with focus on security servers. Very strong in Microsoft Azure cloud!
This entry was posted in AAD. Bookmark the permalink.