12. SpringBoot集成JWT token实现权限验证

1306 字约 3 分钟读完3243 次阅读更新于 2026/5/3

pom JWT 依赖

<!-- JWT -->
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>4.3.0</version>
</dependency>

自定义注解 AuthAccess

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthAccess {
}

GlobalException

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result serviceException(ServiceException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

}

ServiceException

@Getter
public class ServiceException extends RuntimeException {

    private final String code;

    public ServiceException(String msg) {
        super(msg);
        this.code = "500";
    }

    public ServiceException(String code, String msg) {
        super(msg);
        this.code = code;
    }

}

401 是权限错误

自定义拦截器 JwtInterceptor

配置拦截器 InterceptorConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/**")
        super.addInterceptors(registry);
    }

    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

}

工具类 TokenUtils

token
image.png

登录后存储数据
image.png

let user = JSON.parse(localStorage.getItem("honey-user") || '{}')
config.headers['token'] = user.token  // 设置请求头

我们发现请求的头多了一个 token 数据
这个 token 就是登录接口返回的 token
在每次的请求的时候,都会在请求头带上这个 token 作为验证信息
image.png