欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot JWT接口驗證實現(xiàn)流程詳細介紹

 更新時間:2022年09月15日 09:42:07   作者:杼蛘  
這篇文章主要介紹了SpringBoot+JWT實現(xiàn)接口驗證,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧

需求:只有用戶登錄成功后,才能訪問其它接口,否則提示需要進行登錄

項目倉庫地址: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驅(qū)動-->
        <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:
  # 配置數(shù)據(jù)源信息
  datasource:
    # 配置數(shù)據(jù)源類型
    type: com.zaxxer.hikari.HikariDataSource
    # 配置連接數(shù)據(jù)庫的各個信息
    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) {
        // 進行數(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("登錄失敗");
    }
    /**
     * 此處做測試,看用戶在未登錄時,能否訪問到此接口
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R<List<User>> index() {
        return R.success("訪問成功", userService.list());
    }
}

使用攔截器實現(xiàn)

創(chuàng)建JwtInterceptor.java類,實現(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 請求頭中取出 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,實現(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("/**")
                // 排除的請求路徑
                .excludePathPatterns("/user/login");
    }
}

啟動項目,使用ApiPost進行接口測試。首先在未登錄狀態(tài)下,訪問/user/list接口

此時先進行登錄,訪問/user/login接口

復(fù)制登錄時的token放于/user/list接口的請求頭,進行訪問

到此這篇關(guān)于SpringBoot JWT接口驗證實現(xiàn)流程詳細介紹的文章就介紹到這了,更多相關(guān)SpringBoot JWT接口驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java中Socket設(shè)置超時時間的兩種方式

    java中Socket設(shè)置超時時間的兩種方式

    這篇文章主要介紹了java中Socket設(shè)置超時時間的兩種方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • SpringBoot日程管理Quartz與定時任務(wù)Task實現(xiàn)詳解

    SpringBoot日程管理Quartz與定時任務(wù)Task實現(xiàn)詳解

    定時任務(wù)是企業(yè)級開發(fā)中必不可少的組成部分,諸如長周期業(yè)務(wù)數(shù)據(jù)的計算,例如年度報表,諸如系統(tǒng)臟數(shù)據(jù)的處理,再比如系統(tǒng)性能監(jiān)控報告,還有搶購類活動的商品上架,這些都離不開定時任務(wù)。本節(jié)將介紹兩種不同的定時任務(wù)技術(shù)
    2022-09-09
  • java 數(shù)據(jù)結(jié)構(gòu)與算法 (快速排序法)

    java 數(shù)據(jù)結(jié)構(gòu)與算法 (快速排序法)

    這篇文章主要介紹了java 數(shù)據(jù)結(jié)構(gòu)與算法(快速排序法),,快速排序法是實踐中的一種快速的排序算法,在c++或?qū)ava基本類型的排序中特別有用,下面我們一起進入文章學(xué)習(xí)更詳細的內(nèi)容吧,需要的朋友可以參考下
    2022-02-02
  • Dubbo負載均衡策略介紹

    Dubbo負載均衡策略介紹

    負載均衡改善了跨多個計算資源(例如計算機,計算機集群,網(wǎng)絡(luò)鏈接,中央處理單元或磁盤驅(qū)動的的工作負載分布。負載平衡旨在優(yōu)化資源使用,最大化吞吐量,最小化響應(yīng)時間,并避免任何單個資源的過載
    2022-09-09
  • jedis的return行為源碼解析

    jedis的return行為源碼解析

    這篇文章主要為大家介紹了jedis的return行為源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09
  • Mybatis批量插入index out of range錯誤的解決(較偏的錯誤)

    Mybatis批量插入index out of range錯誤的解決(較偏的錯誤)

    這篇文章主要介紹了Mybatis批量插入index out of range錯誤的解決(較偏的錯誤),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java針對ArrayList自定義排序的2種實現(xiàn)方法

    Java針對ArrayList自定義排序的2種實現(xiàn)方法

    這篇文章主要介紹了Java針對ArrayList自定義排序的2種實現(xiàn)方法,結(jié)合實例形式總結(jié)分析了Java操作ArrayList自定義排序的原理與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2018-01-01
  • mybatis框架入門學(xué)習(xí)教程

    mybatis框架入門學(xué)習(xí)教程

    MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架。這篇文章主要介紹了mybatis框架入門學(xué)習(xí)教程,需要的朋友可以參考下
    2017-02-02
  • Java中List排序的三種實現(xiàn)方法實例

    Java中List排序的三種實現(xiàn)方法實例

    其實Java針對數(shù)組和List的排序都有實現(xiàn),對數(shù)組而言你可以直接使用Arrays.sort,對于List和Vector而言,你可以使用Collections.sort方法,下面這篇文章主要給大家介紹了關(guān)于Java中List排序的三種實現(xiàn)方法,需要的朋友可以參考下
    2021-12-12
  • Mybatis查詢返回Map<String,Object>類型的實現(xiàn)

    Mybatis查詢返回Map<String,Object>類型的實現(xiàn)

    本文主要介紹了Mybatis查詢返回Map<String,Object>類型的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07

最新評論