2013-08-14 20 views
17

Potrzebuję zabezpieczyć mój tok internetowy za pomocą podpisu i szyfrowania. Napisałem kolejne linie kodu:Jak zaszyfrować token bezpieczeństwa JWT?

var tokenHandler = new JwtSecurityTokenHandler(); 
var tokenDescriptor = new SecurityTokenDescriptor 
{ 
     Subject = new ClaimsIdentity(new[] 
     { 
      new Claim(ClaimTypes.Name, owner.Name), 
      new Claim(ClaimTypes.Role, owner.RoleClaimType), 
      new Claim("custom claim type", "custom content") 
     }), 
     TokenIssuerName = "self", 
     AppliesToAddress = "http://www.example.com", 
     Lifetime = new Lifetime(now, now.AddSeconds(60 * 3)), 
     EncryptingCredentials = new X509EncryptingCredentials(new X509Certificate2(cert)), 
     SigningCredentials = new X509SigningCredentials(cert1) 
}; 
var token = (JwtSecurityToken)tokenHandler.CreateToken(tokenDescriptor);    
var tokenString = tokenHandler.WriteToken(token); 

Tak, używam kilka certyfikatów, generowanych z makecert.exe. Potem przeczytałem symboliczny łańcuch z innym JwtSecurityTokenHandler:

var tokenHandlerDecr = new JwtSecurityTokenHandler(); 
var tok = tokenHandlerDecr.ReadToken(tokenString); 

i Token treść nie jest zaszyfrowana (widzę json w tok zmiennej pod debugger). Co ja robię źle? Jak szyfrować dane tokena?

Odpowiedz

5

Rozumiem, że implementacja Microsoft JWT nie obsługuje obecnie szyfrowania (tylko podpisywanie).

+0

Jeśli tak, będę naprawdę wdzięczny, gdyby mógł Pan podać mi kilka linków na ten temat. –

+0

Sprawdziłem to rozszerzenie i wygląda na to, że masz rację - szyfrowanie nie jest jeszcze obsługiwane. Dzięki! –

+0

Czy nadal tak jest? –

13

Znam ten stary post, ale dodaję swoją odpowiedź na wypadek, gdyby ktoś nadal szukał odpowiedzi.

Ten numer jest przedmiotem zainteresowania w Microsoft.IdentityModel.Tokens version 5.1.3. Istnieje funkcja przeciążenia dostępna w funkcji CreateJwtSecurityToken, która akceptuje dane uwierzytelniające szyfrowanie w celu zaszyfrowania tokena.

Jeśli odbiornik nie sprawdzi podpisu i spróbuje odczytać JWT, wówczas oświadczenia są puste. Poniżej znajduje się fragment kodu:

using Microsoft.IdentityModel.Tokens; 
using System.IdentityModel.Tokens.Jwt; 

const string sec = "ProEMLh5e_qnzdNUQrqdHPgp"; 
const string sec1 = "ProEMLh5e_qnzdNU"; 
var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec)); 
var securityKey1 = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec1)); 

var signingCredentials = new SigningCredentials(
    securityKey, 
    SecurityAlgorithms.HmacSha512); 

List<Claim> claims = new List<Claim>() 
{ 
    new Claim("sub", "test"), 
}; 

var ep = new EncryptingCredentials(
    securityKey1, 
    SecurityAlgorithms.Aes128KW, 
    SecurityAlgorithms.Aes128CbcHmacSha256); 

var handler = new JwtSecurityTokenHandler(); 

var jwtSecurityToken = handler.CreateJwtSecurityToken(
    "issuer", 
    "Audience", 
    new ClaimsIdentity(claims), 
    DateTime.Now, 
    DateTime.Now.AddHours(1), 
    DateTime.Now, 
    signingCredentials, 
    ep); 


string tokenString = handler.WriteToken(jwtSecurityToken); 

// Id someone tries to view the JWT without validating/decrypting the token, 
// then no claims are retrieved and the token is safe guarded. 
var jwt = new JwtSecurityToken(tokenString); 

A oto kod do sprawdzania/odszyfrować Token:

using Microsoft.IdentityModel.Tokens; 
using System.IdentityModel.Tokens.Jwt; 

const string sec = "ProEMLh5e_qnzdNUQrqdHPgp"; 
const string sec1 = "ProEMLh5e_qnzdNU"; 
var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec)); 
var securityKey1 = new SymmetricSecurityKey(Encoding.Default.GetBytes(sec1)); 

// This is the input JWT which we want to validate. 
string tokenString = string.Empty; 

// If we retrieve the token without decrypting the claims, we won't get any claims 
// DO not use this jwt variable 
var jwt = new JwtSecurityToken(tokenString); 

// Verification 
var tokenValidationParameters = new TokenValidationParameters() 
{ 
    ValidAudiences = new string[] 
    { 
     "536481524875-glk7nibpj1q9c4184d4n3gittrt8q3mn.apps.googleusercontent.com" 
    }, 
    ValidIssuers = new string[] 
    { 
     "https://accounts.google.com" 
    }, 
    IssuerSigningKey = securityKey, 
    // This is the decryption key 
    TokenDecryptionKey = securityKey1 
}; 

SecurityToken validatedToken; 
var handler = new JwtSecurityTokenHandler(); 

handler.ValidateToken(tokenString, tokenValidationParameters, out validatedToken); 
+0

jak odszyfrować token, ponieważ nie ma opcji przekazania klucza podczas sprawdzania tokena? –

+1

@SangSuantak TokenValidationParameters ma właściwość TokenDecryptionKey. Validator wewnętrznie używa tej właściwości do odszyfrowania tokena. Zaktualizowałem moją odpowiedź, aby dołączyć część do deszyfrowania – Amey

+0

dzięki za aktualizację –

Powiązane problemy