Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize the cookie value in MVC5 ASP.NET Identity

I am in the process of changing our authentication implementation to use MVC5 ASP.NET Identity with Owin.

However we need to integrate our sign in with other linked applications and websites on the same domain. We currently do this by sharing the cookie between applications across a number of subdomains. The cookie in a very specific format and encryption algorithm that a variety of applications and technologies (ie not all are in .NET or on the same server) can use.

I have found that in the App_Start ConfigureAuth.cs you can set the app.UseCookieAuthentication to specify things like the cookie name and the subdomain of the cookie (eg ASP.NET Identity Cookie across subdomains).

This is a very good start, but I also need to change the actual value of the cookie to be a specific format and encryption algorithm.

Does anyone know how to customize the value and encryption type used to create and read the cookie?

Thanks for any help, Saan

like image 255
Saan Avatar asked Feb 10 '14 13:02

Saan


1 Answers

CookieAuthenticationOptions class has a property called TicketDataFormat which is meant for this purpose. You can implement a custom ISecureDataFormat object and achieve this. A default has been assigned for this TicketDataFormat if you have not overridden this.

app.UseCookieAuthentication(new CookieAuthenticationOptions() 
{ 
   TicketDataFormat = new MyCustomSecureDataFormat()
});

public class MyCustomSecureDataFormat : ISecureDataFormat<AuthenticationTicket>
{
     private static AuthenticationTicket savedTicket;

     public string Protect(AuthenticationTicket ticket)
     {
         //Ticket value serialized here will be the cookie sent. Encryption stage.
         //Make any changes if you wish to the ticket
         ticket.Identity.AddClaim(new Claim("Myprotectionmethod", "true"));
         return MySerializeAndEncryptedStringMethod(ticket);
     }

     public AuthenticationTicket Unprotect(string cookieValue)
     {
         //Invoked everytime when a cookie string is being converted to a AuthenticationTicket. 
         return MyDecryptAndDeserializeStringMethod(cookieValue);
     }
 }
like image 120
Praburaj Avatar answered Sep 21 '22 19:09

Praburaj