2013-08-14 47 views
17

Tôi cần bảo mật mã thông báo web của mình bằng cách ký tên và mã hóa. Tôi viết những dòng tiếp theo của mã:Làm cách nào để mã hóa mã thông báo bảo mật 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); 

Vì vậy, tôi đang sử dụng một số giấy chứng nhận, được tạo ra với makecert.exe. Sau đó, tôi đọc chuỗi mã thông báo với JwtSecurityTokenHandler khác:

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

Và thẻ nội dung không được mã hóa (tôi có thể thấy json theo tok biến dưới debugger). Tôi đang làm gì sai? Làm cách nào để mã hóa dữ liệu mã thông báo?

Trả lời

5

Sự hiểu biết của tôi là triển khai JWT của Microsoft hiện không hỗ trợ mã hóa (chỉ ký).

+0

Nếu vậy, tôi sẽ thực sự đánh giá cao nếu bạn có thể cung cấp cho tôi với một số liên kết về chủ đề này. –

+0

Tôi đã khám phá phần mở rộng này và có vẻ như bạn đang đúng - mã hóa chưa được hỗ trợ. Cảm ơn! –

+0

Đây có phải là trường hợp không? –

13

Tôi biết điều này là một bài đăng cũ, nhưng tôi đang thêm câu trả lời của mình trong trường hợp có ai đó vẫn đang tìm kiếm câu trả lời.

Sự cố này được giải quyết trong Microsoft.IdentityModel.Tokens version 5.1.3. Có một phương thức quá tải có sẵn trong chức năng CreateJwtSecurityToken chấp nhận thông tin mã hóa để mã hóa mã thông báo.

Nếu người nhận không xác thực chữ ký và cố gắng đọc JWT, thì các xác nhận quyền sở hữu trống. Dưới đây là đoạn mã:

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); 

Và đây là đoạn code để xác nhận/giải mã 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

làm thế nào tôi có thể giải mã mã thông báo vì không có tùy chọn chuyển khóa khi xác thực mã thông báo? –

+1

@SangSuantak TokenValidationParameters có thuộc tính TokenDecryptionKey. Validator sử dụng nội bộ thuộc tính này để giải mã mã thông báo. Tôi đã cập nhật câu trả lời của mình để bao gồm phần giải mã – Amey

+0

cảm ơn vì đã cập nhật –

Các vấn đề liên quan