簡體   English   中英

自定義MVC5 ASP.NET標識中的cookie值

[英]Customize the cookie value in MVC5 ASP.NET Identity

我正在更改我們的身份驗證實現以使用Owin的MVC5 ASP.NET身份。

但是,我們需要將我們的登錄與同一域中的其他鏈接應用程序和網站集成。 我們目前通過在多個子域之間共享應用程序之間的cookie來實現此目的。 Cookie采用非常特定的格式和加密算法,可以使用各種應用程序和技術(即並非所有應用程序和技術都在.NET或同一服務器上)。

我發現在App_Start ConfigureAuth.cs中你可以設置app.UseCookieAuthentication來指定cookie名稱和cookie子域的內容(例如跨子域的ASP.NET Identity Cookie )。

這是一個非常好的開始,但我還需要將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);
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM