Spring Boot 接口验证 Token 的实现

一、整体流程概述

在 Spring Boot 中实现接口验证 Token 通常涉及以下几个步骤:

步骤 描述
1. 引入依赖 pom.xml 中添加相关依赖
2. 配置 Token 在应用配置文件中配置 Token
3. 创建过滤器 自定义过滤器来验证请求中的 Token
4. 应用过滤器 将过滤器注册到 Spring Boot 应用中
5. 测试接口 通过 Postman 或其他工具验证接口

二、流程图展示

flowchart TD
    A[引入依赖] --> B[配置 Token]
    B --> C[创建过滤器]
    C --> D[应用过滤器]
    D --> E[测试接口]

三、步骤详细说明

1. 引入依赖

在你的 pom.xml 文件中,添加以下依赖,用于支持 JWT(JSON Web Token):

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

这段依赖用于生成和验证 JWT Token。

2. 配置 Token

application.properties 文件中,配置相关的 Token 信息:

jwt.secret=mySecretKey
jwt.expiration=86400000

jwt.secret 是生成 JWT 的密钥,jwt.expiration 是 Token 的有效时间(毫秒)。

3. 创建过滤器

在你的项目中,创建一个 JwtAuthenticationFilter 类,用于拦截请求并验证 Token:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${jwt.secret}")
    private String secretKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        // 验证 Token
        if (token != null && validateToken(token)) {
            Claims claims = extractClaims(token);
            // TODO: 你可以将用户信息存储在上下文中
        }

        filterChain.doFilter(request, response);
    }

    private boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private Claims extractClaims(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    }
}

JwtAuthenticationFilter 继承了 OncePerRequestFilter,重写了 doFilterInternal 方法,用于验证请求中的 Token 是否有效。

4. 应用过滤器

在你的 Spring Boot 启动类中,注册该过滤器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        http.csrf().disable().authorizeRequests().anyRequest().authenticated();
    }
}

SecurityConfig 中,我们将自定义的 JwtAuthenticationFilter 注册到 Spring Security 中。

5. 测试接口

使用 Postman 或其他工具发送带有 Authorization 头的请求,验证接口是否能正确返回数据。

四、总结

通过以上步骤,你可以实现 Spring Boot 中接口 Token 的验证。利用 JWT 可以安全地传输用户身份信息,同时保护你的 API。务必确保你的密钥和 Token 有效期的安全管理,以避免安全隐患。如果你还有疑问,欢迎随时发问!