The understanding of token in JWT and the actual results of its advantages and disadvantages are here

JWT: Json Web Token. As the name suggests, it is a scheme that uses Json for Token authorization on the Web.

Since the password is not found, how does the token solve the trust problem?

To solve the trust problem, only two problems need to be solved:

Is the token issued by an organization I trust?

Whether the information in the token has been tampered with

For the first question, it is confirmed that the token is indeed issued by a trusted third party. Generally, the trust is established through an encryption algorithm, and a key is used for encryption when issuing. If the encrypted content can be decrypted normally, it means that the token comes from trusted party. Commonly used encryption algorithms are divided into:

Symmetric reversible encryption: use the same secret key to encrypt and decrypt, if the token can be decrypted, the source can be proved, and the secret key is not disclosed to the public

Asymmetric reversible encryption: use a set of secret key pairs (private key encryption + public key decryption), if the token can be decrypted with the public key, the source can be proved, and the public key and the private key cannot be deduced from each other

Advantages and disadvantages:

Symmetric reversible encryption is efficient and fast, but because symmetric reversible encryption uses the same secret key, the secret key must be provided to the decrypted application, which is relatively insecure, so it is generally only used between internal applications.

The speed of asymmetric reversible encryption is relatively slow, but only the public key needs to be provided when encrypting through private key encryption and decryption, so it is more secure and reliable to provide external encryption mechanism, so it is mostly used when providing encryption services to third parties.

Algorithm example:

HS256
HS256 (HMAC with SHA-256 is a symmetric algorithm where only one key is shared between two parties. Since the same key is used to generate and verify signatures, care must be taken to ensure that the key is not compromised.

2 RS256
RS256 (RSA signature with SHA-256) is an asymmetric algorithm that uses a public/private key pair: the identity provider uses the private key to generate the signature, and the JWT consumer obtains the public key to verify the signature. Since public keys (compared to private keys) do not require protection, most identity providers make it easy for consumers to obtain and use (usually via a metadata URL).

JWT Format Description

JWT token format effect
Header head     { "alg": "HS256", "typ": "JWT"}
Payload Payload Serialize with base64, anyone can read it, so don't include sensitive information
Signature sign

Prevent repudiation - prevent tampering, once the contents of the header and payload are tampered with, the generated signature will be different from the original content

=HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

How does JWT solve the trust problem?

Decrypt the signature part using the secret key. If it can be unlocked normally, it means that the token is issued by a trusted party. Compare the decrypted content with the base64 encoded content of the JWT header and payload. If they are consistent, it means the token Has not been tampered with. It also solves the second problem of token trust.

Algorithm implementation:

The following is the jwt generated using the above two encryption algorithms

HS256 algorithm implementation

 1 public string GetToken(UserInfoDTO userInfo)
 2 {
 3     string secretKey = _configuration["SercetKey"];
 4     var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)), SecurityAlgorithms.HmacSha256);
 5 
 6     var claims = new Claim[] {
 7         new Claim("id",userInfo.Id.ToString()),
 8         new Claim("age",userInfo.Age.ToString()),
 9         new Claim("name",userInfo.Name),
10         new Claim("mobile",userInfo.Mobile),
11         new Claim("email",userInfo.EMail),
12         new Claim("role",userInfo.Role),
13     };
14 
15 var token = new JwtSecurityToken(
16 issuer: _configuration["Issuer"], //issuer
17 audience: _configuration["Audience"], // Audience
18         claims: claims,
19 expires: DateTime.UtcNow.AddMinutes(2), //60 minutes valid
20 notBefore: DateTime.UtcNow.AddMinutes(1),//valid after 1 minute
21         signingCredentials: signingCredentials);
22     string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
23     return returnToken;
24 }

RSA256 algorithm implementation

 1 public string GetToken(UserInfoDTO userInfo)
 2 {
 3     string filepath = Directory.GetCurrentDirectory();
 4     RSAParameters rSAParameter = default(RSAParameters);
 5 // Create a private key file if it has not been generated, otherwise read the private key
 6     if (!File.Exists(Path.Combine(filepath, "key.private.json")))
 7     {
 8         rSAParameter = GenerateAndSaveKey(filepath);
 9     }
10     else
11     {
12         rSAParameter = JsonConvert.DeserializeObject<RSAParameters>(File.ReadAllText(Path.Combine(filepath, "key.private.json")));
13     }
14 
15     var signingCredentials = new SigningCredentials(new RsaSecurityKey(rSAParameter), SecurityAlgorithms.RsaSha256);
16     var claims = new Claim[] {
17         new Claim("id",userInfo.Id.ToString()),
18         new Claim("age",userInfo.Age.ToString()),
19         new Claim("name",userInfo.Name),
20         new Claim("mobile",userInfo.Mobile),
21         new Claim("email",userInfo.EMail),
22         new Claim("role",userInfo.Role),
23     };
24 
25 var token = new JwtSecurityToken(
26 issuer: _configuration["Issuer"], //issuer
27 audience: _configuration["Audience"], // Audience
28         claims: claims,
29 expires: DateTime.UtcNow.AddMinutes(60),//60 minutes valid
30 notBefore: DateTime.UtcNow.AddMinutes(1),//valid after 1 minute
31         signingCredentials: signingCredentials);
32     string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
33     return returnToken;
34 }

Request in postman:

Take the returned jwt to the jwt official website for analysis, and you can see that it already contains the content we need to pass. Because the content passed in jwt can be seen, you must not pass sensitive information such as passwords

Create a webapi project as a protected resource, enable permission authentication, and use jwt as the authentication method

 1 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
 2 .AddJwtBearer(configureOptions =>
 3 {
 4     configureOptions.TokenValidationParameters = new TokenValidationParameters
 5     {
 6         ValidAudience = Configuration["Audience"],
 7         ValidateAudience = true,
 8         ValidIssuer = Configuration["Issuer"],
 9         ValidateIssuer = true,
10         ValidateLifetime = false,
11         LifetimeValidator = (notBefore, expires, securityToken, validationParameters) => {
12             DateTime now = DateTime.UtcNow;
13             if (now.CompareTo(notBefore) < 0 || now.CompareTo(expires) > 0)
14                 return false;
15             return true;
16         },
17 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SercetKey"])), //Symmetric encryption method, get key
18 //IssuerSigningKey = new RsaSecurityKey(GetPulicKey()), //Asymmetric encryption method to obtain the public key provided by the third party
19         ValidateIssuerSigningKey = true,
20          
21     };
22 });

If the protected api is requested without passing the token, 401 will be returned

 

With the obtained token, you can request normally

 

Summary: A JWT consists of three parts: header, payload, signature. Leave a small tail " Medical Records and Proofs ​​​​​​​​​​" and be happy together.

Guess you like

Origin blog.csdn.net/dageliuqing/article/details/127603234