Asp.net
ASP.NET Identity 2.0 解密 Owin cookie
我正在應用多租戶的伺服器端應用程序中工作。在這個伺服器端,我有一個 Backoffice ( ASP.NET MVC ) 和一個 BackEnd ( WCF )。
我想解密身份 cookie,以便我可以檢查它是否有效並使用它在 WCF 服務中進行身份驗證。
更具體地說,我真的很想知道 ASP.NET Identity API 是否提供類似以下範例的任何類型的服務(如果我使用表單身份驗證,它會起作用)
FormsAuthenticationTicket formsTicket = FormsAuthentication.Decrypt(tokenValue);提前致謝。
經過大量研究,我在部落格中找到了一種方法。最終算法如下所示:
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; } } } }請注意,主體就像在發送您剛剛呼叫的身份驗證 cookie 的一方:
HttpContext.Current.User如果你有興趣知道算法是如何工作的,你可以在這裡找到