In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "SpringBoot integration JWT how to achieve token verification", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "SpringBoot integration JWT how to achieve token verification" it!
JWT can be understood as an encrypted string consisting of three parts: header (Header), Payload (payload) and signature (signature).
Used by header and payload encrypted by base64. Concatenate the string, then add salt secret combination encryption through the encryption method declared in header, and then form the JWT string
The previous issue introduced the related concepts and basic operations of JWT, and then introduced how to integrate JWT in SpringBoot to achieve login registration.
Environment building 1. Create a new SpringBoot project Jwt-Demo Introduce the jar package org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.mybatis.spring.boot mybatis-spring-boot-starter 2. 0 that you need to use after introducing the project. 1.3 mysql mysql-connector-java 8.0.25 com.alibaba druid 1.2.1 org.projectlombok lombok 1.18.12 Org.mybatis.spring.boot mybatis-spring-boot-starter-test 2.1.3 com.auth0 java-jwt 3.4.0 2 、 Database structure
There is a JWT library with a User table in it.
3 、 Configuration file application.propertiesserver.port=8989spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/JWT?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=truespring.datasource.username=rootspring.datasource.password=12345678#mybatis scanned package mybatis.type-aliases-package=com.ylc#mapper file path mybatis.mapper-locations=classpath:/**/*.xml# enable sql print log logging.level is followed by the corresponding mybatis The package logging.level.com.ylc.jwtdemo.dao=debug4, where the method interface is located, Create a new User class import lombok.Data under the Entity package @ Datapublic class User {private String username; private String password; private int id;} 5, create a new UserDao@Mapperpublic interface UserDao {User login (User user) under the Dao package;} 6, create a new USerServicepublic interface UserService {User login (User user) under the Service package; / / login interface} 7, the implementation class UserServiceImpimport java.util.HashMap;import java.util.Map;@Servicepublic class UserServiceImpI implements UserService {@ Autowired private UserDao userDao of UseService @ Override public User login (User user) {User userdb=userDao.login (user); if (userdatabase null) {Map map=new HashMap (); map.put ("name", userdb.getUsername ()); return userdb;} throw new RuntimeException ("login failed");}} 8, create a new UserController@RestControllerpublic class UserController {@ Autowired private UserService userService under the controller package @ GetMapping ("/ user/login") public Map login (User user) {log.info ("user name:" + user.getUsername ()); log.info ("password:" + user.getPassword ()); Map map=new HashMap (); try {userService.login (user); map.put ("msg", "login successful") Map.put ("code", "200");} catch (Exception ex) {map.put ("msg", "login failed");} return map }} 9. Create a new Usermapper file under the resource folder: select * from user where username=# {username} and password=# {password} 10, JWT tool class JwtUtils/** * JWT tool class * @ author yanglingcong * @ date, 2021-12-31 11:24 AM * / public class JwtUtils {/ / Authentication equivalent to private static final String secret= "# # @ $% @ # S#WS" / * generate token * @ author yanglingcong * @ date on 2021-12-31 11:23 AM * @ param map * @ return String * / public static String getToken (Map map) {Calendar instance=Calendar.getInstance (); / / default seven-day expired instance.add (Calendar.DATE,7); / / create JWT JWTCreator.Builder builder = JWT.create () / / payload map.forEach ((kmemv)-> {builder.withClaim (krecov);}); / / specify token expiration time builder.withExpiresAt (instance.getTime ()); String token=builder.sign (Algorithm.HMAC256 (secret)); return token } / * verify token * @ author yanglingcong * @ date 11:26 on 2021-12-31 AM * @ param token * / public static DecodedJWT verify (String token) {return JWT.require (Algorithm.HMAC256 (secret)). Build () .verify (token);}}
An overview of the entire project
Test to verify that you can connect to the database
Visit: localhost:8989/user/login?username=ylc&password=123456
Introduce JWT@Slf4j@RestControllerpublic class UserController {@ Autowired private UserService userService; @ GetMapping ("/ user/login") public Map login (User user) {log.info ("username:" + user.getUsername ()); log.info ("password:" + user.getPassword ()); Map map=new HashMap (); try {userService.login (user) Map.put ("msg", "login successful"); map.put ("code", "200"); Map payload=new HashMap (); payload.put (" name ", user.getUsername ()); String token= JwtUtils.getToken (payload); map.put (" token ", token) } catch (Exception ex) {map.put ("msg", "login failed");} return map;} @ PostMapping ("/ test/verity") public Map verityToken (String token) {Map map=new HashMap (); log.info ("token is" + token); try {DecodedJWT verify = JwtUtils.verify (token) Map.put ("msg", "verification successful"); map.put ("state", "true");} catch (Exception exception) {map.put ("msg", "authentication failure"); exception.printStackTrace ();} return map;}} login operation
Visit: http://localhost:8989/user/login?username=ylc&password=123456
Verification operation
Visit: http://localhost:8989/test/verity
But it is unreasonable for us to write this in the actual project. The code generated by token is put in Controller, and the business logic cannot be placed in the Controller layer. If many interfaces need token for authentication protection, then each interface needs to add such a piece of code, resulting in code redundancy.
Program optimization
If the web project uses interceptors for optimization, and if the springcloud project intercepts at the gateway level, the following shows how to use interceptors to intercept
It is also best to put the JWT generation token in the http request header, so that you do not need to pass token as a parameter
Create a new interceptor JwtInterceptor
/ * JWT interceptor * @ author yanglingcong * @ date 12:39 on 2021-12-31 PM * / public class JwtInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HashMap map=new HashMap (); / / get token String token = request.getHeader ("token") from the http request header Try {/ / if verification succeeds, release request DecodedJWT verify = JwtUtils.verify (token); return true;} catch (Exception exception) {map.put ("msg", "verification failed:" + exception);} String json = new ObjectMapper () .writeValueAsString (map); response.setContentType ("application/json:charset=UTF=8") Response.getWriter () .println (json); return false;}
Then register the interceptor with the filter and create a new filter InterceptConfig
/ * * @ author yanglingcong * / @ Configurationpublic class InterceptConfig implements WebMvcConfigurer {@ Override public void addInterceptors (InterceptorRegistry registry) {/ / add interceptor registry.addInterceptor (new JwtInterceptor ()) / / the path intercepted requires token verification. AddPathPatterns ("/ test/verity") / / release path .innovdePathPatterns ("/ user/login") }}
Login does not need to be intercepted. If other requests need to verify token, put them into the path of the interceptor.
Test verification
Putting token in the http request header will be intercepted by the interceptor to verify the validity of the token.
At this point, I believe that everyone has a deeper understanding of "SpringBoot integration JWT how to achieve token verification", might as well come to the actual operation! 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.