微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 自定义MVC5 ASP.NET标识中的cookie值

我正在更改我们的身份验证实现以使用Owin的MVC5 ASP.NET身份.

但是,我们需要将我们的登录与同一域中的其他链接应用程序和网站集成.我们目前通过在多个子域之间共享应用程序之间的cookie来实现此目的. Cookie采用非常特定的格式和加密算法,可以使用各种应用程序和技术(即并非所有应用程序和技术都在.NET或同一服务器上).

我发现在App_Start ConfigureAuth.cs中你可以设置app.UseCookieAuthentication来指定cookie名称和cookie子域的内容(例如ASP.NET Identity Cookie across subdomains).

这是一个非常好的开始,但我还需要将cookie的实际值更改为特定格式和加密算法.

有谁知道如何自定义用于创建和读取cookie的值和加密类型?

谢谢你的帮助,
Saan

解决方法

CookieAuthenticationoptions类有一个名为TicketDataFormat的属性,用于此目的.您可以实现自定义的ISecureDataFormat对象并实现此目的.如果您没有覆盖此TicketDataFormat,则已为此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);
     }
 }

原文地址:https://www.jb51.cc/csharp/243291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐