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/01 Report--
This article focuses on "how to achieve authorized access to the interface based on JWT", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to implement authorized access to interfaces based on JWT".
What is JWT?
JWT (JSON Web Token) is an open standard (RFC 7519), which defines a compact and independent way to securely transmit information between systems using JSON as an object, and to ensure that the transmitted information will not be tampered with.
There are usually two application scenarios for JWT:
Authorization. This is the most common JWT usage scenario. Once the user logs in, each subsequent request will contain a JWT as the user's token to access the resource.
information switching. JWT can be used to securely transmit information between systems, and the nature of JWT enables the receiver to verify whether the received content has been tampered with.
This article discusses the first point, how to use JWT to achieve authorized access to API. In this way, only authorized users can call API.
The structure of JWT
JWT consists of three parts, using. Split it up.
Header
The first part is Header, which usually consists of two parts: the type of token, JWT, and the encryption algorithm used.
{"alg": "HS256", "typ": "JWT"}
When Base64 is encrypted, it becomes:
EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9Payload
The second part is Payload, which can place custom information, as well as expiration time, issuer and so on.
{"sub": "1234567890", "name": "John Doe", "iat": 1516239022}
When Base64 is encrypted, it becomes:
EyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQSignature
The third part is Signature, which requires four pieces of information to calculate this signature:
Algorithm information in Header
Header
Payload
A custom key
After receiving the JWT, the signature is calculated again with the same information, and then compared with the signature in JWT, if it is different, the content in JWT has been tampered with.
Decoded JWT
Encode all the above three parts and then combine them together to get JWT.
It is important to note that the content of JWT is not encrypted, just simple Base64 encoding. In other words, once JWT is leaked, the information in it can be easily accessed, so you should not use JWT to save any sensitive information.
How does JWT work
The application or client requests authorization from the authorization server. The license server here can be a separate application, or it can be integrated with API in the same application.
The authorization server returns a JWT to the application.
The application puts the JWT into the request (usually in the Authorization header of the HTTP)
After receiving the request, the server verifies the JWT and executes the corresponding logic.
Using JWT to introduce dependent io.jsonwebtoken jjwt in JAVA
A library called JJWT (Java JWT) is used here.
JWT Service generates JWTpublic String generateToken (String payload) {return Jwts.builder () .setSubject (payload) .setExpiration (new Date (System.currentTimeMillis () + 10000)) .signWith (SignatureAlgorithm.HS256, SECRET_KEY) .compact ();}
Here the expiration time is set to 10 seconds, so the generated JWT can only be verified in 10 seconds.
You need to provide a custom key.
Decode JWTpublic String parseToken (String jwt) {return Jwts.parser () .setSigningKey (SECRET_KEY) .parseClaimsJws (jwt) .getBody () .getSubject ();}
The signature of the JWT is checked during decoding, so you need to provide the secret key.
Verify JWTpublic boolean isTokenValid (String jwt) {try {parseToken (jwt);} catch (Throwable e) {return false;} return true;}
JWT does not provide a way to determine whether a JWT is legal, but an exception is thrown when decoding an illegal JWT, so you can determine whether it is legal by catching an exception.
Register / log in @ GetMapping ("/ registration") public String register (@ RequestParam String username, HttpServletResponse response) {String jwt = jwtService.generateToken (username); response.setHeader (JWT_HEADER_NAME, jwt); return String.format ("JWT for% s:\ n% s", username, jwt);}
You need to provide a registration or login entry for users who have not yet obtained the JWT to obtain the JWT.
After getting the JWT in the response, include the JWT in the subsequent request, which is placed in the Authorization header of the request.
Verify JWT@Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String jwt = httpServletRequest.getHeader (JWT_HEADER_NAME); if (WHITE_LIST.contains (httpServletRequest.getRequestURI () {chain.doFilter (request, response);} else if (isTokenValid (jwt)) {updateToken (httpServletResponse, jwt) Chain.doFilter (request, response);} else {httpServletResponse.sendError (HttpServletResponse.SC_UNAUTHORIZED);}} private void updateToken (HttpServletResponse httpServletResponse, String jwt) {String payload = jwtService.parseToken (jwt); String newToken = jwtService.generateToken (payload); httpServletResponse.setHeader (JWT_HEADER_NAME, newToken);}
Put the authentication operation in the Filter so that other business code will not feel the existence of JWT except for the login entry.
Place the login entries in WHITE_LIST and skip the validation of these entries.
The JWT needs to be refreshed. If JWT is legal, you should use the same Payload to generate a new JWT, so that the new JWT will have a new expiration time, and use this operation to refresh the JWT to prevent expiration.
If you use Filter, the refresh operation should be done before calling doFilter (), because the response can no longer be modified after the call.
APIprivate final static String JWT_HEADER_NAME = "Authorization"; @ GetMapping ("/ api") public String testApi (HttpServletRequest request, HttpServletResponse response) {String oldJwt = request.getHeader (JWT_HEADER_NAME); String newJwt = response.getHeader (JWT_HEADER_NAME); return String.format ("Your old JWT is:\ n% s\ nYour new JWT is:\ n% s\ n", oldJwt, newJwt);}
At this point, API is under the protection of JWT. API can not be aware of the existence of JWT at all. At the same time, it can also actively obtain JWT and decode it to get the information in JWT. As shown above.
At this point, I believe you have a deeper understanding of "how to implement authorized access to the interface based on JWT". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.