Spring|Spring Boot整合JWT的实现步骤
springboot整合jwt步骤:
1、登录时,验证账号和密码成功后,生成jwt,返回给前端;
2、前端接收后保存,再做其他操作,比如增删改查时,同时将jwt传给后端进行验证,如果jwt当做参数一起传给后端,那么每个操作都会有jwt,为了方便,把jwt放到请求头中,通过拦截器来验证。
代码
代码结构图如下,除了常规的controller、entity、mapper和service层,还有两个拦截器和注册拦截器,图中用红字进行注释(这篇文章稍微有点长,因为我把代码都放上来了,结合下边的思路和结构图就能理解个大概)。
思路:有请求过来,通过拦截器进行拦截,但放行登录请求,如果登录成功,生成JWT令牌,返回给前端,当前端再有其他请求过来时,拦截器会拦截并解析token,如果通过就允许业务操作,否则就返回相应提示信息。
文章图片
1、创建jwt数据库,然后创建user表
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(255) DEFAULT NULL,`password` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
插入数据
INSERT INTO `user` VALUES (1, 'zhangsan', '123'); INSERT INTO `user` VALUES (2, 'lisi', '123');
2、创建Spring Boot项目,在pom文件中,添加jwt等一些依赖和properties:
com.auth0 java-jwt3.4.0 org.projectlombok lombokorg.mybatis.spring.boot mybatis-spring-boot-starter2.1.4 com.alibaba druid1.2.4 mysql mysql-connector-java5.1.47 org.springframework spring-tx5.3.8
编写application.properties
server.port=8899spring.application.name=jwtspring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/jwt?useSSL=true&characterEncoding=utf-8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=rootmybatis.type-aliases-package=com.jwt.entitymybatis.mapper-locations=classpath:mapper/*Mapper.xml#打印sqllogging.level.com.jwt.mapper=debug
3、编写代码 3.1、编写entity包下的User类
public class User {private String id; private String username; private String password; //省略了get和set方法}
3.2、编写util包下的JWTUtils类
public class JWTUtils {private static final String SING = "lu123456"; /*** 生成token*/public static String getToken(Map map){Calendar instance = Calendar.getInstance(); //默认7天过期instance.add(Calendar.DATE,7); //创建jwt builderJWTCreator.Builder builder = JWT.create(); map.forEach((k,v)->{builder.withClaim(k,v); }); String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SING)); return token; }/*** 验证token合法性*/public static DecodedJWT verify(String token){return JWT.require(Algorithm.HMAC256(SING)).build().verify(token); }}
3.3、编写controller层下UserController类
@RestController@Slf4jpublic class UserController {@Autowiredprivate UserService userService; @GetMapping("/user/login")public Map login(User user){log.info("用户名:[{}]",user.getUsername()); log.info("密码:[{}]",user.getPassword()); Map map = new HashMap<>(); try {User userDB = userService.login(user); Map payload = new HashMap<>(); payload.put("id",userDB.getId()); payload.put("username",userDB.getUsername()); //生成JWT令牌String token = JWTUtils.getToken(payload); map.put("state",true); map.put("token",token); map.put("msg","认证成功"); }catch (Exception e){map.put("state",false); map.put("msg",e.getMessage()); }return map; }@PostMapping("/user/test")public Map test(String token){Map map = new HashMap<>(); map.put("state",true); map.put("msg","请求成功"); return map; }}
3.4、编写service层下UserService类和UserServiceImpl 类
public interface UserService {User login (User user); }
实现类:
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper; @Override@Transactional(propagation = Propagation.SUPPORTS)public User login(User user) {//查询数据库User userDB = userMapper.login(user); if (userDB != null){return userDB; }throw new RuntimeException("登录失败"); }}
【Spring|Spring Boot整合JWT的实现步骤】3.5、编写mapper层的UserMapper类
@Mapperpublic interface UserMapper {User login(User user); }
3.6、编写与UserMapper 对应的UserMapper.xml
SELECT * FROM user WHERE username = #{username} AND password = #{password}
3.7、配置拦截器,这样得到jwt后,再次请求时把jwt放到请求头中,就可以不用当参数传递。
编写JWTInterceptor类:
/** * 配置拦截器 */public class JWTInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Map map = new HashMap<>(); //获取请求头中的令牌String token = request.getHeader("token"); try {//验证令牌DecodedJWT verify = JWTUtils.verify(token); return true; } catch (SignatureVerificationException e){e.printStackTrace(); map.put("msg","无效签名"); } catch (TokenExpiredException e){e.printStackTrace(); map.put("msg","token过期"); } catch (AlgorithmMismatchException e){e.printStackTrace(); map.put("msg","token算法不一致"); } catch (Exception e){e.printStackTrace(); map.put("msg","token无效"); }map.put("state","flase"); //将map转为jsonString json = new ObjectMapper().writeValueAsString(map); response.setContentType("application/json; charset=UTF-8"); response.getWriter().println(json); return false; }}
编写InterceptorConfig类:
/** * 注册拦截器 */@Configurationpublic class InterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new JWTInterceptor())//拦截.addPathPatterns("/user/test")//放行.excludePathPatterns("/user/login"); }}
4、测试
运行程序后,使用postman进行测试,登录如下图
请求方式:
get
url:
http://localhost:8899/user/login?username=zhangsan&password=123
然后点击send,就会看到返回成功和token
文章图片
请求测试
请求方式:
post
url:
http://localhost:8899/user/test
点击header,在请求头中添加token,然后点击send
文章图片
到此这篇关于Spring Boot整合JWT的文章就介绍到这了,更多相关Spring Boot整合JWT内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- Activiti(一)SpringBoot2集成Activiti6
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 2018-07-09|2018-07-09 Spring 的DBCP,c3p0
- spring|spring boot项目启动websocket
- Spring|Spring Boot 整合 Activiti6.0.0
- Spring集成|Spring集成 Mina
- springboot使用redis缓存
- Spring|Spring 框架之 AOP 原理剖析已经出炉!!!预定的童鞋可以识别下发二维码去看了
- Spring|Spring Boot之ImportSelector