SpringBoot+JWT实现接口验证

14 篇文章 0 订阅
13 篇文章 0 订阅

需求:只有用户登录成功后,才能访问其它接口,否则提示需要进行登录
项目仓库地址: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接口的请求头,进行访问
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杼蛘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值