JWT整合Springboot
程序员文章站
2022-03-02 23:37:26
JWT实战步骤什么是JWTJWT长什么样?JWT的构成创建Springboot项目pom.xmlapplication.propertiesmapper.xml创建JWT工具类创建domain创建Dao层创建service层创建Controller创建注解类创建Config创建拦截器测试步骤(postman)什么是JWTJson web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点...
JWT实战步骤
什么是JWT
Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。
JWT长什么样?
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJleHAiOjE2MDYzODMwODN9.Xd5t2G2yEzS-rP4hMVtMEqQ42Z2IWegxSATuUFjQXco
JWT的构成
header
{
'typ': 'JWT',
'alg': 'HS256'
}
playload
{
"id": "1",
"name": "zhangsan"
}
signature
private static final String SING="LIUYISHOU@Token666";
Algorithm.HMAC256(SING)
创建Springboot项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.11.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xjw</groupId>
<artifactId>myjwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myjwt</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<!--引入mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--引入lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<!--引入druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<!--引入mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
<version>2.6.4</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jwt?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
mybatis.type-aliases-package=com.xjw.domain
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.com.xjw.dao=debug
mapper.xml
文件目录:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xjw.dao.UserDao">
<select id="login" parameterType="User" resultType="User">
select id,name,password from user where name=#{name} and password=#{password}
</select>
</mapper>
创建JWT工具类
package com.xjw.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xjw.domain.User;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Component
public class JWTUtils {
/**
* 盐值
*/
private static final String SING="LIUYISHOU@Token666";
public String getToken(User user) {
Map<String, String> map = new HashMap<>();
map.put("name", user.getName());
return this.getToken(map);
}
/**
* 生成令牌
* @param map payload载荷声明参数
* @return
*/
public String getToken(Map<String,String> map){
//获取日历对象
Calendar calendar=Calendar.getInstance();
//默认7天过期
calendar.add(Calendar.DATE, 7);
//新建一个JWT的Builder对象
JWTCreator.Builder builder = JWT.create();
//将map集合中的数据设置进payload
map.forEach((k,v)->{
builder.withClaim(k, v);
});
//设置过期时间和签名
String sign = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SING));
return sign;
}
/**
* 验签并返回DecodedJWT
* @param token 令牌
*/
public DecodedJWT getTokenInfo(String token){
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}
}
创建domain
package com.xjw.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private Integer id;
private String name;
private String password;
}
创建Dao层
package com.xjw.dao;
import com.xjw.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao {
/**
* 登录方法
* @param user
* @return
*/
User login(User user);
}
创建service层
package com.xjw.service.impl;
import com.xjw.dao.UserDao;
import com.xjw.domain.User;
import com.xjw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User login(User user) {
//接受用户查询数据库
User userDB = userDao.login(user);
//查询到这个用户就返回,没有则抛出错误
if (userDB != null) {
return userDB;
}else{
throw new RuntimeException("登录失败!");
}
}
}
package com.xjw.service;
import com.xjw.domain.User;
import org.springframework.stereotype.Service;
@Service
public interface UserService {
/**
* 登录方法
* @param user
* @return
*/
User login(User user);
}
创建Controller
package com.xjw.control;
import com.alibaba.fastjson.JSONObject;
import com.xjw.annota.UserLoginToken;
import com.xjw.domain.User;
import com.xjw.service.UserService;
import com.xjw.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("api")
@Slf4j
public class UserApi {
@Autowired
UserService userService;
@Autowired
JWTUtils jWTUtils;
//登录
@PostMapping("/login")
public Object login(@RequestBody User user){
JSONObject jsonObject=new JSONObject();
log.info("用户名:[{}]",user.getName());
log.info("密码:[{}]",user.getPassword());
//登录用户
User userDB = userService.login(user);
if(userDB == null){
jsonObject.put("message","登录失败,用户不存在");
return jsonObject;
}else {
if (!userDB.getPassword().equals(user.getPassword())){
jsonObject.put("message","登录失败,密码错误");
return jsonObject;
}else {
String token = jWTUtils.getToken(userDB);
jsonObject.put("token", token);
return jsonObject;
}
}
}
@UserLoginToken
@PostMapping("/query")
public String query(@RequestBody User user){
JSONObject jsonObject=new JSONObject();
log.info("用户名:[{}]",user.getName());
log.info("密码:[{}]",user.getPassword());
//登录用户
User userDB = userService.login(user);
return JSONObject.toJSONString(userDB);
}
}
创建注解类
package com.xjw.annota;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
package com.xjw.annota;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
创建Config
package com.xjw.config;
import com.xjw.intercepter.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}
创建拦截器
package com.xjw.intercepter;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xjw.annota.PassToken;
import com.xjw.annota.UserLoginToken;
import com.xjw.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
JWTUtils jWTUtils;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
Map<String, String> map = new HashMap<>();
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(object instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod=(HandlerMethod)object;
Method method=handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//校验token
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("无token,请重新登录");
}
try {
jWTUtils.getTokenInfo(token);
map.put("msg","身份验证成功");
} 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无效");
}
if ("身份验证成功".equals(map.get("msg").toString())) {
return true;
}else {
throw new RuntimeException(map.get("msg"));
}
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
测试步骤(postman)
首先登陆
查询:
故意写错token
本文地址:https://blog.csdn.net/xiejianweifdd/article/details/109820478