在MVC5 ASP.NET Identity中自定义cookie的值

7
我正在将我们的身份验证实现更改为使用MVC5 ASP.NET Identity with Owin。但是,我们需要将登录与同一域上的其他链接应用程序和网站集成。我们目前通过在多个子域之间共享cookie来实现此操作。Cookie采用非常特定的格式和加密算法,各种应用程序和技术(即不是所有.NET或位于同一服务器上的应用程序)都可以使用。
我发现在App_Start ConfigureAuth.cs中,您可以设置app.UseCookieAuthentication以指定诸如cookie名称和cookie的子域(例如ASP.NET Identity Cookie across subdomains)等内容。
这是一个很好的开始,但我还需要更改cookie的实际值为特定的格式和加密算法。
有人知道如何自定义用于创建和读取cookie的值和加密类型吗?
感谢任何帮助, Saan
1个回答

13

CookieAuthenticationOptions类有一个叫做TicketDataFormat的属性,专门用于这个目的。您可以实现自定义的ISecureDataFormat对象并实现此操作。如果您没有覆盖它,则会为TicketDataFormat分配默认值。

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);
     }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接