返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBootJWT接口验证实现流程详细介绍
  • 302
分享到

SpringBootJWT接口验证实现流程详细介绍

2024-04-02 19:04:59 302人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录添加pom.xml修改配置文件创建简单的测试接口使用拦截器实现需求:只有用户登录成功后,才能访问其它接口,否则提示需要进行登录 项目仓库地址:https://gitee.com/

需求:只有用户登录成功后,才能访问其它接口,否则提示需要进行登录

项目仓库地址: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;
    
    @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("登录失败");
    }
    
    @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接口验证内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBootJWT接口验证实现流程详细介绍

本文链接: https://lsjlt.com/news/167587.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作