Springboot整合JWT连接数据库篇(三)

环境与实现步骤:

1、Springboot+Mybatis-plus+JWT+MySQL(数据库)

2、pom文件中引入依赖

3、编写配置文件

4、代码实现部分

5、SQL部分

6、postman请求

一、依赖部分

        <!--JWT-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>

二、配置文件

# 应用名称
spring.application.name=Springboot-jwt
# 应用服务 WEB 访问端口
server.port=8080

# 数据库相关配置
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-test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

三、代码部分

  3.1、代码结构

    

  3.2、代码部分

  config代码

/**
 *  指定拦截路径
 */
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
                // 配置 拦截器
                .addInterceptor(new JWTInterceptor())

                // 配置 拦截路径
                .addPathPatterns("/user/test")

                // 配置 排除路径模式
                .excludePathPatterns("/user/getLogin");
    }
}

  controller代码

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService us;

    // 以用户登录为例
    @GetMapping("/getLogin")
    public String getLogin(){
        Map<String, String> map = new HashMap<>();
        map.put("id","1");
        map.put("username","xiaoming");

        String token = JWTUtil.getToken(map);

        System.out.println(token);
        return token;
    }

    @PostMapping("/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader("token");
        //验证token
        DecodedJWT verify = JWTUtil.verify(token);
        String id = verify.getClaim("id").asString(); // 我前⾯存的时候转字符串了
        String name = verify.getClaim("username").asString();

        System.out.println(id);
        System.out.println(name);

        //TODO:模拟业务逻辑
        Map<String, Object> map = new HashMap<>();
        //根据USer对象查询数据库
        UserDO req = new UserDO();
        req.setId(Integer.valueOf(id));
        req.setUserName(name);

        UserDO res = us.getUserDO(req);
        if(res!=null){
            map.put("data",res);
            map.put("msg", "请求成功");
        }else {
            map.put("msg", "请求失败");
        }

        return map;
    }
}

   dao代码

public interface UserDao extends BaseMapper<UserDO> {

}

  interceptor代码

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("token");

        Map<String, Object> map = new HashMap<>();
        try {
            JWTUtil.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "签名不⼀致");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "令牌过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "算法不匹配");
        } catch (InvalidClaimException e) {
            e.printStackTrace();
            map.put("msg", "失效的payload");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token⽆效");
        }
        map.put("status", false);
        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

}

  UserDO代码

@TableName("user")
public class UserDO implements Serializable {
    @TableId
    private Integer id;

    @TableField("username")
    private String userName;

    @TableField("password")
    private String passWord;

   public UserDO(Integer id, String userName, String passWord) {
        this.id = id;
        this.userName = userName;
        this.passWord = passWord;
    }

    public UserDO() {
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    @Override
    public String toString() {
        return "UserDO{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                '}';
    }
}

  Service代码

public interface UserService {

    public UserDO getUserDO(UserDO userDO);

}
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao ud;

    // 根据UserDO对象查询一条数据
    @Override   
    public UserDO getUserDO(UserDO userDO){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",userDO.getUserName());
        queryWrapper.eq("id",userDO.getId());

        UserDO userDB = ud.selectOne(queryWrapper);

        return userDB;
    }
    
}

  Util代码

public class JWTUtil {
     //秘钥自己保管好
        private static String SECRET = "token!Q@W3e4r";
        /**
         * 生成token
         * @param map  //传入payload
         * @return 返回token
         */
        public static String getToken(Map<String,String> map){
            JWTCreator.Builder builder = JWT.create();
            map.forEach((k,v)->{
                builder.withClaim(k,v);
            });
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.DATE,3);//默认3天过期

            builder.withExpiresAt(instance.getTime());//指定过期时间
            return builder.sign(Algorithm.HMAC256(SECRET));
        }


        /**
         * 验证token
         * @param token
         * @return
         */
        // 有任何验证异常,此处都会抛出
        public static DecodedJWT verify(String token){
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }


        /**
         * 获取token中payload数据
         * @param token
         * @return
         */
        public static Map<String, Claim> getPayloadFromToken(String token) {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();
        }
}

  application代码

@MapperScan("com.gao.jwt.dao")
@SpringBootApplication
public class JwtApplication {

    public static void main(String[] args) {
        SpringApplication.run(JwtApplication.class, args);
    }
    
}

四、SQL部分

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'xiaoming', '123456');
INSERT INTO `user` VALUES ('2', 'xiaohong', '123');
INSERT INTO `user` VALUES ('3', 'xiaogao', '321654');
INSERT INTO `user` VALUES ('4', 'xiaoxiao', '789');

五、postman测试

5.1、获取JWTtoken

5.2、解析JWTtoken

posted @ 2023-02-26 19:07  向大海  阅读(239)  评论(0编辑  收藏  举报