这篇文章主要介绍了SpringBoot+JWT实现接口验证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
需求:只有用户登录成功后,才能访问其它接口,否则提示需要进行登录
项目仓库地址:https://gitee.com/aiw-nine/springboot_jwt_verify
添加pom.xml
新建Spring Boot(2.7.2)项目,添加如下依赖:
<?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.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.eaiw</groupId>
<artifactId>springboot_jwt_verify</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_jwt_verify</name>
<description>springboot_jwt_verify</description>
<properties>
<java.version>17</java.version>
<mysql.version>5.1.40</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 引入jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
</dependency>
<!--MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--redis缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
修改配置文件
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库的各个信息
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
创建简单的测试接口
package com.aiw.springboot_jwt_verify.controller;
import com.aiw.springboot_jwt_verify.entity.User;
import com.aiw.springboot_jwt_verify.response.R;
import com.aiw.springboot_jwt_verify.service.UserService;
import com.aiw.springboot_jwt_verify.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 登录,此处只做简单测试
*
* @param user
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public R<Map> login(@RequestBody User user) {
// 进行数据库查询
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getName, user.getName()).eq(User::getPwd, user.getPwd());
User one = userService.getOne(wrapper);
if (Objects.nonNull(one)) {
// 登录成功,根据用户id生成token并返回登录成功结果
Map<String, Object> map = new HashMap<>();
map.put("user", one);
map.put("token", JwtUtil.sign(one.getId()));
return R.success("登录成功", map);
}
return R.fail("登录失败");
}
/**
* 此处做测试,看用户在未登录时,能否访问到此接口
*
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public R<List<User>> index() {
return R.success("访问成功", userService.list());
}
}
使用拦截器实现
创建JwtInterceptor.java
类,实现HandlerInterceptor
接口
package com.aiw.springboot_jwt_verify.interceptor;
import com.aiw.springboot_jwt_verify.response.R;
import com.aiw.springboot_jwt_verify.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从 http 请求头中取出 token
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
if (Objects.nonNull(token) && JwtUtil.verify(token)) {
return true;
}
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未通过身份认证")));
return false;
}
}
注册拦截器,新建配置类WebConfig.java
,实现WebMvcConfigurer
接口
package com.aiw.springboot_jwt_verify.config;
import com.aiw.springboot_jwt_verify.interceptor.JwtInterceptor;
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 WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
.addPathPatterns("/**")
// 排除的请求路径
.excludePathPatterns("/user/login");
}
}
启动项目,使用ApiPost进行接口测试。首先在未登录状态下,访问/user/list
接口
此时先进行登录,访问/user/login接口
复制登录时的token
放于/user/list
接口的请求头,进行访问
到此这篇关于SpringBoot JWT接口验证实现流程详细介绍的文章就介绍到这了,更多相关SpringBoot JWT接口验证内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:SpringBoot JWT接口验证实现流程详细介绍
基础教程推荐
- springboot自定义starter方法及注解实例 2023-03-31
- Java实现线程插队的示例代码 2022-09-03
- java实现多人聊天系统 2023-05-19
- JDK数组阻塞队列源码深入分析总结 2023-04-18
- java基础知识之FileInputStream流的使用 2023-08-11
- Java数据结构之对象比较详解 2023-03-07
- Java并发编程进阶之线程控制篇 2023-03-07
- Java文件管理操作的知识点整理 2023-05-19
- Java实现查找文件和替换文件内容 2023-04-06
- ConditionalOnProperty配置swagger不生效问题及解决 2023-01-02