The encrypted jwt information is shown below and consists of three parts, namely header, payload and signature.
eyjhbgcioijuzi 1 nij 9 . eyjqdgkioijqd 3 qilcjpyxqioj 0 nzeynzyyntesin n 1 yi i6 intcinvzzxjjzfwiojesxcjyb 2 xlswrcijovisimv 4c ci 6 mtq 3 mtmxot q 1 MX 0 . VW-ppsl 5 bu 4d mora 7 uzpjbr 0 f 6 sqg 3 hquky 8j 35 o
Header contains two parts of information, alg refers to the encryption type, and the optional values are HS256, RSA, etc. , and typ=JWT is a fixed value indicating the type of token.
{
" alg": "HS256 ",
Typical: JWT
}
Payload refers to signature information and content, generally including iss (publisher), exp (expiration time), sub (user information), aud (receiver) and other information. Please refer to official website for details.
{
" sub": " 1234567890 ",
Name: anonymous,
Management: true
}
A signature is the signature of the header and payload.
hmacsha 256(base64 urlencode(header)+"。" +base64UrlEncode (payload), confidential)
You can see that there are different language versions in jwt official website, and the Java version of jjwt is used here. Not much to say, look at the code directly, encryption and decryption are very simple:
/**
* create jwt
* @param id
* @param theme
* @param ttlMillis
* @ Return
* @ throws an exception
*/
The public string createJWT (string id, string subject, long ttlMillis) throws an exception {
signature algorithm signature algorithm = signature algorithm。 HS256
long nowMillis = System。 current time millis();
Date now = new date (now millis);
secret key key = general key();
JwtBuilder builder = Jwts。 The builder ()
. Set Id
. SetIssuedAt (now)
. SetSubject (topic)
. signWith(signatureAlgorithm,key);
if(TTL millis & gt; = 0){
long exp millis = now millis+TTL millis;
Date exp = new date (expmillis);
builder . set expiration(exp);
}
Returns builder.compact ();
}
/**
* decrypt jwt
* @param jwt
* @ Return
* @ throws an exception
*/
The public declaration parseJWT (string JWT) threw an exception {
secret key key = general key();
Claim claim = Jwts. Analyzer ()
. SetSigningKey (key)
. parseClaimsJws( jwt)。 getBody();
Claim for return of goods;
}
The encryption key is generated by conversion of fixed character strings; Subject is the json string of user information; TtlMillis refers to the validity period of token, which is relatively short and needs to be updated regularly.
The token refresh method to be introduced here is to generate a refreshToken with a long validity period while generating the token, and then the client will get the latest token according to the refreshToken regularly. Establish sse (Server Send Event) request between the browser and the server to achieve refresh. Sse was introduced in the previous blog post, so I will skip it here.