ASP.NET Identity 2.0解密Owin cookie [英] ASP.NET Identity 2.0 decrypt Owin cookie
问题描述
我在一个服务器端应用程序中,我正在申请多租户。在此服务器端,我有一个后台( ASP.NET MVC )和一个后端( WCF )。
I'm working in a server-side application where I'm applying multi tenancy. In this server side I have a Backoffice (ASP.NET MVC) and a BackEnd (WCF).
我想解密Identity cookie,以便我可以检查它是否有效,并将其用于WCF服务中的身份验证。
I want to decrypt Identity cookie so that I can check that it is valid and use it to auth in WCF Services.
更具体地说,我真的想知道如果ASP .NET Identity API提供任何类型的服务,如下面的示例(如果我使用表单验证,它会工作)
To be more specific I really want to know if ASP.NET Identity API provides any kind of service like the following example (it would work if I was using forms Authentication)
FormsAuthenticationTicket formsTicket = FormsAuthentication.Decrypt(tokenValue);
提前感谢。
推荐答案
经过大量的研究,我发现了一种在博客中做到这一点的方法。最终的算法如下:
After a lot of research I found a way to do this in a blog. The final algorithm looks like the following:
private bool BackOfficeUserAuthorized(string ticket)
{
ticket = ticket.Replace('-', '+').Replace('_', '/');
var padding = 3 - ((ticket.Length + 3) % 4);
if (padding != 0)
ticket = ticket + new string('=', padding);
var bytes = Convert.FromBase64String(ticket);
bytes = System.Web.Security.MachineKey.Unprotect(bytes,
"Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
"ApplicationCookie", "v1");
using (var memory = new MemoryStream(bytes))
{
using (var compression = new GZipStream(memory,
CompressionMode.Decompress))
{
using (var reader = new BinaryReader(compression))
{
reader.ReadInt32();
string authenticationType = reader.ReadString();
reader.ReadString();
reader.ReadString();
int count = reader.ReadInt32();
var claims = new Claim[count];
for (int index = 0; index != count; ++index)
{
string type = reader.ReadString();
type = type == "\0" ? ClaimTypes.Name : type;
string value = reader.ReadString();
string valueType = reader.ReadString();
valueType = valueType == "\0" ?
"http://www.w3.org/2001/XMLSchema#string" :
valueType;
string issuer = reader.ReadString();
issuer = issuer == "\0" ? "LOCAL AUTHORITY" : issuer;
string originalIssuer = reader.ReadString();
originalIssuer = originalIssuer == "\0" ?
issuer : originalIssuer;
claims[index] = new Claim(type, value,
valueType, issuer, originalIssuer);
}
var identity = new ClaimsIdentity(claims, authenticationType,
ClaimTypes.Name, ClaimTypes.Role);
var principal = new ClaimsPrincipal(identity);
return principal.Identity.IsAuthenticated;
}
}
}
}
意识到主体就像在发送您刚刚调用的auth cookie的一侧:
HttpContext.Current.User
如果您有兴趣了解算法的工作原理,您可以找到这里
If you are interested in know how the algorithm works you can find it here
这篇关于ASP.NET Identity 2.0解密Owin cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!