In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to analyze and practice JSON WEB TOKEN. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
1. JSON WEB TOKEN1.1 what is JWT
JSON Web Token (JWT) is a very lightweight specification.
This specification allows us to use JWT to communicate secure and reliable information between the user and the server. Referred to as JWT, identity authentication is carried out in the process of HTTP communication.
We know that HTTP communication is stateless, so the client's request cannot be returned to the original client after it has been processed by the server.
Therefore, it is necessary to identify the clients that are accessed, which is commonly done through the session mechanism:
After the client has successfully logged in on the server, the server will generate a sessionID and return it to the client. The client will save the sessionID to the cookie. When it initiates the request again, it will bring the sessionID in the cookie to the server, and the server will cache the session (session). When the client request arrives, the server will know which user's request it is, and return the processing result to the client to complete the communication.
From the above analysis, we can see that session has the following problems:
1. The session is stored on the server. When the customer visits increase, the server needs to store a large number of session sessions, which is a great test for the server.
2. When the server is a cluster, the user logs in to one of the servers and saves the session to the memory of the server, but when the user accesses other servers, it will not be accessible. It is usually inconvenient to use cache consistency technology to ensure that the session can be shared, or to use a third-party cache to save the server.
1.2 how does Json Web Token do it?
The client logs in to the server with a username and password
The server verifies the identity of the client
The server generates Token for the user and returns it to the client.
The client initiates a request and needs to carry the Token
After receiving the request, the server first verifies the Token and then returns the data.
The client saves the Token to a local browser, usually to cookie.
The server does not need to save the Token, but only needs to verify the information carried in the Token.
No matter which server the client accesses in the background, as long as it can pass the verification of the user information.
1.3Principle of JWT
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": "Zhang San", "role": "Administrator", "Expiration time": "00:00 on October 31, 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.
1.4 data structure of JWT
The actual JWT looks something like this.
Cdn.xitu.io/2019/5/27/16af725bdcb5a01e?w=800&h=184&f=jpeg&s=22269 ">
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 parts of JWT are as follows.
Header (head)
Payload (load)
Signature (signature)
Write it on a line, and that's what it looks like.
1.4.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 algorithm of the signature (algorithm), and the default is HMAC SHA256 (written as HS256); the typ attribute indicates the token (type), and the JWT token is always written as JWT.
Finally, the above JSON object is converted to a string using the Base64URL algorithm (see later).
1.4.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}
Note that 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.
1.4.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.
1.4.4 Base64URL
As mentioned earlier, the algorithm for serialization of Header and Payload is Base64URL. This algorithm is basically similar to the Base64 algorithm, but with some small differences.
JWT, as a token, may be put into URL in some situations (such as api.example.com/?token=xxx).
Base64 has three characters +, / and =, which have a special meaning in URL, so they have to be replaced: = is omitted, + is replaced with -, / is replaced with _. This is the Base64URL algorithm.
1.5 ways to use JWT
The client receives the JWT returned by the server, which can be stored in Cookie or localStorage.
Since then, the client will bring this JWT with it every time it communicates with the server. You can send it automatically in Cookie, but it's not cross-domain, so it's better to put it in the header Authorization field of the HTTP request.
Authorization: Bearer
Alternatively, when crossing domains, the JWT is placed in the data body of the POST request.
1.6 several 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.
In order to reduce embezzlement, JWT should not use the HTTP protocol for plain code transmission, but should use the HTTPS protocol for transmission.
two。 Tear a Demo by hand
Create a maven project and add pom dependencies:
Io.jsonwebtoken jjwt 0.9.0 junit junit RELEASE compile org.apache.maven.plugins maven-compiler-plugin 3.5 1.8 1.8
Create the class JWTDemo:
Public class JWTDemo {/ / encrypted private static final String SECRET_KEY = "123456789"; @ Test public void jwtTest () throws InterruptedException {/ / set 3 seconds to expire SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); long time = System.currentTimeMillis () + 30 seconds 60 million 1000; String jwt = this.buildJwt (new Date (time)); System.out.println ("jwt =" + jwt) / / verify that token is available boolean isOk = this.isJwtValid (jwt); System.out.println (isOk) } public String buildJwt (Date exp) {String jwt = Jwts.builder () .signWith (SignatureAlgorithm.HS256, SECRET_KEY) / / SECRET_KEY is the key corresponding to the encryption algorithm The amount used here is the HS256 encryption algorithm .setExpiration (exp) / / expTime is the expiration time. Claim ("name", "wangtingjun") .claim ("age", "18") .claim ("key", "vaule") / / the method adds a key field with the value of vaule to the JWT. Compact () Return jwt } public boolean isJwtValid (String jwt) {try {/ / parses the data in the JWT string and performs the most basic verification that Claims claims = Jwts.parser () .setSigningKey (SECRET_KEY) / / SECRET_KEY is the key corresponding to the encryption algorithm Jjwt can automatically determine that the secret algorithm. ParseClaimsJws (jwt) / / jwt is a JWT string .getBody () System.out.println (claims); String vaule = claims.get ("key", String.class); / / get the custom field key / / determine whether the custom field is correct if ("vaule" .equals (vaule)) {return true;} else {return false }} / / when parsing a JWT string, if the key is incorrect, the parsing will fail, and a SignatureException exception will be thrown, indicating that the JWT string is forged / / when parsing the JWT string, if the 'expiration field' is already earlier than the current time, an ExpiredJwtException exception will be thrown Indicates that this request has expired catch (SignatureException | ExpiredJwtException e) {return false }}}
Finally, you can see the printed information on the console.
Jwt = eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDA5NzgxMzAsIm5hbWUiOiJ3YW5ndGluZ2p1biIsImFnZSI6IjE4Iiwia2V5IjoidmF1bGUifQ.XEDlK0UNTV3aKANQe9QCE2Y7JiP7D7ebrDVOs2JxRCQ {exp=1540978130, name=wangtingjun, age=18, key=vaule} true on how to analyze and practice JSON WEB TOKEN to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.