SpringBoot JWT接口驗(yàn)證實(shí)現(xiàn)流程詳細(xì)介紹
需求:只有用戶登錄成功后,才能訪問其它接口,否則提示需要進(jìn)行登錄
項(xiàng)目倉庫地址:https://gitee.com/aiw-nine/springboot_jwt_verify
添加pom.xml
新建Spring Boot(2.7.2)項(xiàng)目,添加如下依賴:
<?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驅(qū)動(dòng)--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mybatis-plus啟動(dòng)器--> <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:
# 配置數(shù)據(jù)源信息
datasource:
# 配置數(shù)據(jù)源類型
type: com.zaxxer.hikari.HikariDataSource
# 配置連接數(shù)據(jù)庫的各個(gè)信息
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
創(chuàng)建簡單的測試接口
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) { // 進(jìn)行數(shù)據(jù)庫查詢 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)) { // 登錄成功,根據(jù)用戶id生成token并返回登錄成功結(jié)果 Map<String, Object> map = new HashMap<>(); map.put("user", one); map.put("token", JwtUtil.sign(one.getId())); return R.success("登錄成功", map); } return R.fail("登錄失敗"); } /** * 此處做測試,看用戶在未登錄時(shí),能否訪問到此接口 * * @return */ @RequestMapping(value = "/list", method = RequestMethod.GET) public R<List<User>> index() { return R.success("訪問成功", userService.list()); } }
使用攔截器實(shí)現(xiàn)
創(chuàng)建JwtInterceptor.java
類,實(shí)現(xiàn)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 請(qǐng)求頭中取出 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("未通過身份認(rèn)證"))); return false; } }
注冊攔截器,新建配置類WebConfig.java
,實(shí)現(xiàn)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("/**") // 排除的請(qǐng)求路徑 .excludePathPatterns("/user/login"); } }
啟動(dòng)項(xiàng)目,使用ApiPost進(jìn)行接口測試。首先在未登錄狀態(tài)下,訪問/user/list
接口
此時(shí)先進(jìn)行登錄,訪問/user/login接口
復(fù)制登錄時(shí)的token
放于/user/list
接口的請(qǐng)求頭,進(jìn)行訪問
到此這篇關(guān)于SpringBoot JWT接口驗(yàn)證實(shí)現(xiàn)流程詳細(xì)介紹的文章就介紹到這了,更多相關(guān)SpringBoot JWT接口驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中Socket設(shè)置超時(shí)時(shí)間的兩種方式
這篇文章主要介紹了java中Socket設(shè)置超時(shí)時(shí)間的兩種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11SpringBoot日程管理Quartz與定時(shí)任務(wù)Task實(shí)現(xiàn)詳解
定時(shí)任務(wù)是企業(yè)級(jí)開發(fā)中必不可少的組成部分,諸如長周期業(yè)務(wù)數(shù)據(jù)的計(jì)算,例如年度報(bào)表,諸如系統(tǒng)臟數(shù)據(jù)的處理,再比如系統(tǒng)性能監(jiān)控報(bào)告,還有搶購類活動(dòng)的商品上架,這些都離不開定時(shí)任務(wù)。本節(jié)將介紹兩種不同的定時(shí)任務(wù)技術(shù)2022-09-09java 數(shù)據(jù)結(jié)構(gòu)與算法 (快速排序法)
這篇文章主要介紹了java 數(shù)據(jù)結(jié)構(gòu)與算法(快速排序法),,快速排序法是實(shí)踐中的一種快速的排序算法,在c++或?qū)ava基本類型的排序中特別有用,下面我們一起進(jìn)入文章學(xué)習(xí)更詳細(xì)的內(nèi)容吧,需要的朋友可以參考下2022-02-02Mybatis批量插入index out of range錯(cuò)誤的解決(較偏的錯(cuò)誤)
這篇文章主要介紹了Mybatis批量插入index out of range錯(cuò)誤的解決(較偏的錯(cuò)誤),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java針對(duì)ArrayList自定義排序的2種實(shí)現(xiàn)方法
這篇文章主要介紹了Java針對(duì)ArrayList自定義排序的2種實(shí)現(xiàn)方法,結(jié)合實(shí)例形式總結(jié)分析了Java操作ArrayList自定義排序的原理與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-01-01Java中List排序的三種實(shí)現(xiàn)方法實(shí)例
其實(shí)Java針對(duì)數(shù)組和List的排序都有實(shí)現(xiàn),對(duì)數(shù)組而言你可以直接使用Arrays.sort,對(duì)于List和Vector而言,你可以使用Collections.sort方法,下面這篇文章主要給大家介紹了關(guān)于Java中List排序的三種實(shí)現(xiàn)方法,需要的朋友可以參考下2021-12-12Mybatis查詢返回Map<String,Object>類型的實(shí)現(xiàn)
本文主要介紹了Mybatis查詢返回Map<String,Object>類型的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07