SoFunction
Updated on 2025-03-07

Operational practice method

definition

JWT (Json Web Token) is a concise and URL-safe expressive declaration specification used to convey security information between the two parties. As an open standard (RFC 7519), JWT defines a concise, self-contained method for safely delivering information between the two parties in the form of Json objects. Because of the existence of digital signatures, this information is trustworthy, and JWT can sign using the HMAC algorithm or RSA's public and private key pair.

Components of

(1) JWT is generally composed of three segments, separated by . numbers. The first segment is header, the second segment is payload, and the third segment is signature.

For example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

use

First of all, you need to introduce it first, you can add it through nuget: Install-Package JWT -Version 2.4.2 (choose the appropriate version yourself)

(1) Create a token. Here, we only need to customize the payload and secret keys to generate a string in three-part format

var payload = new Dictionary<string, object>
{
 { "claim1", 0 },
 { "claim2", "claim2-value" }
};
var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
 
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
 
var token = (payload, secret);
(token);

(2) Token decryption, you can see that the output is { "claim1": 0, "claim2": "claim2-value" }, you can use json["claim1"] and json["claim2"] token decryption, you can see that the output is { "claim1": 0, "claim2": "claim2-value" }, you can use json["claim1"] and json["claim2"] to get each value. Here, json is IDictionary<string,object> type token decryption, you can see that the output is { "claim1": 0, "claim2": "claim2-value" }, you can use json["claim1"] and json["claim2"] to get each value. Here, json is IDictionary<string,object> type

var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s";
var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
try
{
 IJsonSerializer serializer = new JsonNetSerializer();
 IDateTimeProvider provider = new UtcDateTimeProvider();
 IJwtValidator validator = new JwtValidator(serializer, provider);
 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
 IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
 
 var json = (token, secret, verify: true);
 (json);
}
catch (TokenExpiredException)
{
 ("Token has expired");
}
catch (SignatureVerificationException)
{
 ("Token has invalid signature");
}

(3) Add expiration time, which means that the JWT will not accept processing after this time. The valid value of the time is the number of seconds that differs between a certain moment and 1970/1/1 00:00:00

The following example is the number of seconds from the current time to 1970/1/1 00:00:00, that is, the expiration time is the current time. If set to the current time +10 seconds, add secondsSinceEpoch=secondsSinceEpoch+10

IDateTimeProvider provider = new UtcDateTimeProvider();
var now = ();
 
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, ); // or use 
var secondsSinceEpoch = ((now - unixEpoch).TotalSeconds);
 
var payload = new Dictionary<string, object>
{
 { "exp", secondsSinceEpoch }
};
var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
var token = (payload, secret);
 
var json = (token, secret); // TokenExpiredException

(4) You can also customize the json parser, as long as you inherit the IJsonSerializer interface

public class CustomJsonSerializer : IJsonSerializer
{
 public string Serialize(object obj)
 {
 // Implement using favorite JSON Serializer
 }
 
 public T Deserialize<T>(string json)
 {
 // Implement using favorite JSON Serializer
 }
}

Use this parser

IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new CustomJsonSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

The above article is all the content shared by the editor. I hope it can give you a reference and I hope you can support me more.