如果您想尝试第二种方法,请尝试使用此 github 存储库中的 asp.net 票证桥。我用它来促进在 asp.net 核心和 Web 表单身份验证之间共享单一身份 - 只需记住同步加密密钥......希望这会有所帮助!
您将需要创建自己的“ISecureDataFormat”实现:
public class OWINAuthenticationDataFormat<TData> : ISecureDataFormat<TData>
where TData : AuthenticationTicket
{
public OWINAuthenticationOptions Options { get; set; }
...
public string Protect(TData data)
{
return Protect(data, null);
}
..
public string Protect(TData data, string purpose)
{
string decryptionKey = Options.DecryptionKey;
string validation = Options.ValidationMethod;
string validationKey = Options.ValidationKey;
string decryption = Options.EncryptionMethod;
var claimsIdentity = data.Principal.Identity as ClaimsIdentity;
var authTicket = new OwinAuthenticationTicket(claimsIdentity, data.Properties);
// Encrypt the token
return MachineKeyTicketProtector.ProtectCookie(authTicket, decryptionKey, validationKey, decryption, validation);
}
...
public TData Unprotect(string protectedText)
{
return Unprotect(protectedText, null);
}
...
public TData Unprotect(string protectedText, string purpose)
{
string decryptionKey = Options.DecryptionKey;
string validation = Options.ValidationMethod;
string validationKey = Options.ValidationKey;
string decryption = Options.EncryptionMethod;
// Decrypt the token
var ticket = MachineKeyTicketUnprotector.UnprotectCookie(protectedText, decryptionKey, validationKey, decryption, validation);
return new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(ticket.Identity), ticket.Properties, "") as TData;
}
}
之后,在添加 cookie 身份验证时使用它(仍在 asp.net 核心应用程序中):
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts =>
{
opts.Cookie = new CookieBuilder()
{
Domain = CookieDomain,
Name = CookieName,
Path = CookiePath,
SecurePolicy = CookieSecurePolicy.Always
};
opts.TicketDataFormat = new OWINAuthenticationDataFormat<AuthenticationTicket>()
{
Options = new OWINAuthenticationOptions()
{
DecryptionKey = DecryptionKey,
EncryptionMethod = DecryptionAlgorithm,
ValidationKey = ValidationKey,
ValidationMethod = ValidationAlgorithm
}
};
});
请记住在两个应用程序中使用相同的签名密钥和算法!