In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use JWT in Java language, the article is very detailed, has a certain reference value, interested friends must read it!
Characteristics of JWT
JWT is not encrypted by default, but it can be encrypted. After the original Token is generated, it can be encrypted again with the key.
Secret data cannot be written to JWT without JWT encryption.
JWT can be used not only for authentication, but also for the exchange of information. Effective use of JWT can reduce the number of times the server queries the database.
The biggest disadvantage of JWT is that because the server does not save the session state, it cannot abolish a token or change the permissions of token during use. That is, once the JWT is signed, it will remain valid until it expires, unless the server deploys additional logic.
JWT itself contains authentication information, and once disclosed, anyone can get all the privileges of the token. To reduce embezzlement, the validity period of JWT should be set to be short. For some of the more important permissions, users should be authenticated again when using them.
1. The principle of JWT
Jwt official website: https://jwt.io/
The principle of JWT is that after the server is authenticated, a JSON object is generated and sent back to the user, as shown below.
{"name": "John Doe", "role": "Administrator", "expiration time": "00:00 on July 1st, 2018"}
In the future, when the user communicates with the server, the JSON object will be sent back. The server relies entirely on this object to identify the user. To prevent users from tampering with data, the server will add a signature when generating this object (see later).
The server does not save any session data, that is, the server becomes stateless, making it easier to extend.
2. Data structure of JWT
JWT probably looks like this.
EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
EyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4
GRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
It is a long string separated into three parts by a dot (.). Note that there is no line wrapping inside the JWT, and it is written into a few lines just for presentation purposes.
The three components of JWT are as follows.
Header (head)
Payload (load)
Signature (signature)
# write it on one line, and it looks like the following Header.Payload.Signature2.1 Header
The Header part is a JSON object that describes the metadata of the JWT, usually like this.
{"alg": "HS256", "typ": "JWT"}
In the above code, the alg attribute represents the signature algorithm (algorithm), and the default is HMAC SHA256 (written as HS256); the typ attribute indicates the type of the token (type), and the JWT token is written as JWT.
Finally, convert the above JSON object to a string using the Base64URL algorithm.
2.2 Payload
The Payload part is also a JSON object that holds the data that actually needs to be passed. JWT specifies seven official fields to choose from.
Iss (issuer): issuer
Exp (expiration time): expiration time
Sub (subject): topic
Aud (audience): audience
Nbf (Not Before): effective time
Iat (Issued At): time of issue
Jti (JWT ID): number
In addition to official fields, you can also define private fields in this section. Here is an example
{"sub": "1234567890", "name": "John Doe", "admin": true}
JWT is unencrypted by default and can be read by anyone, so don't put secret information in this section.
This JSON object is also converted to a string using the Base64URL algorithm.
2.3 Signature
The Signature part is the signature of the first two parts to prevent data tampering.
First, you need to specify a key (secret). This key is known only to the server and cannot be disclosed to the user. Then, using the signature algorithm specified in Header (default is HMAC SHA256), generate the signature according to the following formula.
HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)
After calculating the signature, the three parts Header, Payload, and Signature are put together into a string. Each part is separated by a "dot" (.), and it can be returned to the user.
3. Use in Java
Dependent, jjwt is used here
Io.jsonwebtoken jjwt 0.9.1
Use
Class DemoApplicationTests {/ / salt key private String secret = "jwtSecretValue"; public static void main (String [] args) {/ / create token String token = this.createToken (20); / / String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.L1cCfQpCSzPOrxbHVqiMaT8ndRlZd2PuHzYE2TIqUA0"; System.out.println ("token->" + token); / / parse token this.parseToken (token) } / / create token public String createToken (Integer time) {/ / expiration time. Default is 10 seconds expiration time = time = = null? 10: time; long l = new Date (). GetTime () + time * 1000; Date expire = new Date (l); / / Custom information Map map = new HashMap (); map.put ("name", "admin") JwtBuilder claim = Jwts.builder () / / sets the signature algorithm and salting key. SignWith (SignatureAlgorithm.HS256 Secret) / / set expiration time .setExpiration (expire) / / Custom content accepts a map .setClaims (map) / unique id {"id": "9527"} .setId ("9527") / / body of JWT {"sub": "jwtSubject"} .setSubject ("jwtSubject") / / issue time of jwt {"iat": "1618383146"} .setIssuedAt (new Date ()) / / Custom content {"name": "admin"} / / .claim ("name", "admin"); String token = claim.compact (); / / parse token, jwt is Base64-encoded / / String [] ts = token.split ("\."); / / for (String s: ts) {/ / System.out.print (s + "- >"); / / System.out.println (Base64Codec.BASE64.decodeToString (s)) / /} / / System.out.println ("= ="); return token;} / parse token public void parseToken (String token) {System.out.println ("= start parsing JWT="); System.out.println ("token->" + token); try {Claims body = Jwts.parser () / / signature key .setSigningKey (secret) / / jwt .parseClaimsJws (token) .getBody () to be parsed System.out.println ("id->" + body.getId ()); System.out.println ("sub->" + body.getSubject ()); System.out.println ("Custom content name->" + body.get ("name")); System.out.println ("iat creation time->" + body.getIssuedAt ()); Date expiration = body.getExpiration (); System.out.print ("Expiration time->") System.out.println (expiration = = null? Expiration: expiration.toLocaleString ();} catch (Exception e) {e.printStackTrace (); System.out.println ("invalid Token");} System.out.println ("= end of JWT parsing =");}}
These are all the contents of the article "how to use JWT in the Java language". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.