In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about how to use JWT. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
1. Define
JWT referred to as JSON Web Token, through the form of JSON as a token in the Web application, the information is safely transmitted between the parties as JSON objects, and data encryption, signature and other related processing can be completed in the process of data transmission.
two。 Role 2.1 Authorization
The most common scheme of JWT, once the user logs in, each subsequent request will include JWT, thus allowing access to the system's resources, which is generally suitable for single sign-on systems because of the low overhead and easy to use in different domains.
2.2 Information exchange
JWT is a good way to securely transfer information between parties, because JWT can be signed, such as using public or private key pairs, because the signature is calculated using headers and payloads, and you can verify that the content has been tampered with.
JWT is different from Session. JWT is stored on the client and Session is stored on the server. When the server is powered off, the Session will be destroyed, while the JWT will not be affected because it is stored on the client. As long as the JWT does not expire, it can continue to be used.
3. Advantage 3.1 based on Session certification
Session is stored in memory, and with the increase of authenticated users, the cost of the server will increase significantly.
After the user authentication, the server makes the authentication record. If the authentication record is kept in memory, it means that the user must request on this server for the next request in order to get the authorized resources. In the distributed system, it limits the ability of the load balancer and the scalability of the application.
CSRF cross-site forgery request attack, Session is based on Cookie for user identification, if the Cookie is intercepted, users will be vulnerable to cross-site request forgery attack.
Sessionid is an eigenvalue, the information expressed is not rich enough, it is not easy to expand, and if the back-end application is multi-node deployment, it is necessary to implement session sharing mechanism, which is not convenient for cluster applications.
3.2 based on JWT authentication
3.2.1 Certification process
The front end sends its user name and password to the back-end interface through the Web form, usually for the http post request, which is encrypted through SSL as far as possible to avoid disclosure of sensitive information.
After the backend successfully checks the user name and password, the user's id and other information is used as the JWT load, and the Base64 code is stitched with the header respectively, and then signed. The resulting JWT is a string in the form of lll.zzz.xxx in the format of head.payload.signature.
The backend returns the JWT string to the front end as the result of a successful login, and the front end can save the returned result on localStorage or sessionStorage. When logging out, the front end deletes the saved JWT.
In order to solve the XSS and XSRF problems, the front end puts the JWT in the authorization location in the http head on each request.
The backend checks whether it exists, if so, verifies the validity of the JWT, checks whether the signature is correct, checks whether the Token expires, and checks whether the recipient of the Token is itself.
After the verification is passed, the backend uses the user information contained in the JWT to perform other logical operations and return the corresponding results.
3.2.2 Features
Concise, can be sent through the Url and Http parameters or in the Http request header, because the amount of data is small and the transmission speed is very fast.
Self-contained, the load contains all the information needed by users, avoiding multiple queries to the database.
Token is stored on the client in the form of JSON encryption, so JWT is cross-language and is supported in principle in any Web form.
There is no need to save session information on the server, so it is especially suitable for distributed micro-services.
4. Jwt structure
Token string = = > header.payload.singnature token
4.1 token composition
Header (Header)
Payload (Payload)
Signature (Signature)
Therefore, the JWT usually looks like this: xxxxx.yyyyy.zzzzz Header.Payload.Signature
4.2 Header
The header usually consists of two parts: the type of token and the signature algorithm used, such as HMAC SHA256 or RSA, which uses Base64 coding to form the first part of the JWT structure.
Base64 is a kind of coding that can be translated back to its original form. It is not an encryption process.
{"alg": "HS256", "typ": "JWT"} 4.3 Payload
The second part of the token is the payload, which contains the declaration. Declarations are declarations about entities and other data, and also use Base64 coding to make up the second part of the JWT structure.
{"sub": "1234567890", "name": "John Doe", "admin": true} 4.4 Signature
The first two parts are encoded using Base64, that is, the front end can get the information inside. Signature needs to use the encoded header and payload as well as a key we provide, and then sign using the signature algorithm specified in header (HS256).
The purpose of the signature is to ensure that the JWT has not been tampered with, such as HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret).
If you decode the header and the payload, modify it, then encode it, and finally add the previous signature combination to form a new JWT, then the server will determine that the signature formed by the new header and payload is different from the signature attached to the JWT. If you want to sign the new header and payload, if you do not know the key used by the server for encryption, the signature obtained is also different.
In JWT, you should not add any sensitive data to the payload.
4.5 final result
5. SpringBoot integrates jwt
Pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.3.RELEASE org.example springboot-jwt-token 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-web com.auth0 Java-jwt 3.10.3 org.projectlombok lombok true org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 mysql mysql-connector-java 8.0.18 com.alibaba druid 1.1.23 org.springframework.boot spring-boot-maven-plugin
Application.properties
Spring.application.name=jwtspring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC&useSSL=falsespring.datasource.username=rootmybatis.type-aliases-package=com.alfred.beanmybatis.mapper-locations=classpath:com/alfred/mapper/*.xmllogging.level.com.alfred.dao=debug
Mybatis xml mapping file
Select * from tb_user where name = # {name} and password = # {password}
Entity class
@ Data@Accessors (chain = true) public class User {private String id; private String name; private String password;}
Dao layer
@ Mapperpublic interface UserDao {/ * login * * @ param user User object * @ return User object * / User login (User user);}
Service layer
User * / User login (User user) queried in user * @ return database in public interface UserService {/ * login interface * * @ param user form;} @ Servicepublic class UserServiceImpl implements UserService {@ Resource private UserDao userDAO; @ Transactional (propagation = Propagation.SUPPORTS) @ Override public User login (User user) {User userDb = userDAO.login (user) If (userDb! = null) {return userDb;} throw new RuntimeException ("Authentication failure");}}
Jwt utility class
Public class JwtUtil {private static String SECRET = "hell world"; / * * generate the token * * @ param map map collection * @ return token * / public static String getToken (Map map) {JWTCreator.Builder builder = JWT.create (); map.forEach (builder::withClaim); Calendar calendar = Calendar.getInstance (); calendar.add (Calendar.HOUR, 12) Return builder.sign (Algorithm.HMAC256 (SECRET));} / * * token * * @ param token token string * @ return authentication interface * / public static DecodedJWT verify (String token) {return JWT.require (Algorithm.HMAC256 (SECRET)). Build (). Verify (token);}}
Interceptor
@ Slf4jpublic class JwtInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / get token in request header String token = request.getHeader ("token"); log.info ("current token is: {}", token); Map map = new HashMap (); try {JwtUtil.verify (token); return true } catch (SignatureVerificationException e) {e.printStackTrace (); map.put ("msg", "signature inconsistency");} catch (TokenExpiredException e) {e.printStackTrace (); map.put ("msg", "token expired");} catch (AlgorithmMismatchException e) {e.printStackTrace () Map.put ("msg", "algorithm mismatch");} catch (InvalidClaimException e) {e.printStackTrace (); map.put ("msg", "invalid payload");} catch (Exception e) {e.printStackTrace (); map.put ("msg", "token invalid") } map.put ("state", false); / / respond to the front desk: convert map to json String json = new ObjectMapper () .writeValueAsString (map); response.setContentType ("application/json;charset=UTF-8"); response.getWriter () .println (json); return false } @ Configurationpublic class InterceptorConfig implements WebMvcConfigurer {@ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new JwtInterceptor ()) .addPathPatterns ("/ user/test") .origindePathPatterns ("/ user/login");}}
Controller layer
@ RestController@Slf4jpublic class UserController {@ Resource private UserService userService; @ GetMapping ("/ user/login") public Map login (User user) {log.info ("user name: {}", user.getName ()); log.info ("password: {}", user.getPassword ()); Map map = new HashMap (); try {User userDb = userService.login (user) Map payload = new HashMap (); payload.put ("id", userDb.getId ()); payload.put ("name", userDb.getName ()); String token = JwtUtil.getToken (payload); map.put ("state", true); map.put ("msg", "login successful"); map.put ("token", token) Return map;} catch (Exception e) {e.printStackTrace (); map.put ("state", false); map.put ("msg", e.getMessage ()); map.put ("token", ");} return map } @ PostMapping ("/ user/test") public Map test (HttpServletRequest request) {String token = request.getHeader ("token"); DecodedJWT verify = JwtUtil.verify (token); String id = verify.getClaim ("id"). AsString (); String name = verify.getClaim ("name"). AsString (); log.info ("id: {}", id) Log.info ("user name: {}", name); / / TODO business logic Map map = new HashMap (); map.put ("state", true); map.put ("msg", "request successful"); return map }} above is how the JWT shared by the editor is used. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are 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.