user505210
user505210

Reputation: 1402

adding claims to forms authentication in asp.net

I have been working on a asp.net application which uses windows azure tables as data storage for users information.I have a class which does the insertion and creation of tables and handles other stuff. When I see that a user is already present I want to issue a authentication token using something like

FormsAuthentication.SetAuthCookie(user,true)  

and I also want to add the user's claims that I got from the windows azure table storage so I can read them later using something like

ClaimsPrincipal claimsPrincipal = Page.User as ClaimsPrincipal; 

Can someone please suggest me how to achieve this? I finished the other parts of this custom app but not very clear how to make this part work.

Thanks

Upvotes: 8

Views: 7543

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48250

This is almost as simple, with the help of the SessionAuthenticationModule.

SessionAuthenticationModule sam = 
    (SessionAuthenticationModule)
    this.Context.ApplicationInstance.Modules["SessionAuthenticationModule"];

IClaimsPrincipal principal = 
   new ClaimsPrincipal( new GenericPrincipal( new GenericIdentity( txtUserName.Text ), null ) );

// create any userdata you want. by creating custom types of claims you can have
// an arbitrary number of your own types of custom data
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.Email, "[email protected]" ) );
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.UserData, ReallyLongUserData ) );

var token = 
  sam.CreateSessionSecurityToken( 
     principal, null, DateTime.Now, DateTime.Now.AddMinutes( 20 ), false );
sam.WriteSessionTokenToCookie( token );

Response.Redirect( this.Context.Request.QueryString["ReturnUrl"] );

Full article that also includes web.config entries:

http://www.wiktorzychla.com/2012/09/forms-authentication-revisited.html

Upvotes: 6

Related Questions