SpringBoot 2.1.1 + SpringSecurity+jwt 去掉Token验证
发布日期:2021-05-13 19:18:39 浏览次数:16 分类:精选文章

本文共 3030 字,大约阅读时间需要 10 分钟。

Spring Boot 2.1.1 + Spring Security + JWT 实现无 Token 验证配置

项目环境

本项目基于以下环境配置:

  • Spring Boot: Version 2.1.1
  • Spring Security: Version 5.1.2
  • JWT: Version 0.9.0

项目结构

com.example
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ ├── controller
│ │ └── security
│ │ ├── config
│ │ ├── filter
│ │ └── handler
│ └── resources
│ ├── static
│ └── templates

安全配置

1. SecurityConfig 类设置

SecurityConfig 类中进行以下配置:

import org.springframework.security.config.annotation.web.HttpSecurityConfigurer;
import org.springframework.security.web.authentication.authenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@Configuration
public class SecurityConfig extends HttpSecurityConfigurer {
private LogoutSuccessHandler logoutSuccessHandler;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 关键点 1:禁用 CSRF 保护
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.authorizeRequests()
.antMatchers("/login").anonymous()
.antMatchers("GET", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
.antMatchers("/**").anonymous()
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
// 关键点 2:启用 JWT 过滤器,确保 Token 解析
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 登录处理
httpSecurity.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler);
}
// ...
}

2. JWT 过滤器配置

JwtAuthenticationTokenFilter 类中设置 JWT 解析规则:

import io.jsonwebtoken.Jwt;
import org.springframework.security.authentication.AuthenticationFilter;
import org.springframework.security.authentication.AuthenticationToken;
import org.springframework.security.authentication {};
/**
* 简单的 JWT 验证过滤器
*
* @author 小天使
*/
public class JwtAuthenticationTokenFilter extends AnonymousAuthenticationFilter {
// ...
}

依赖管理

pom.xml 中添加以下依赖:

org.springframework.boot
spring-boot-starter-security
io.jsonwebtoken
jjwt
${jwt.version}

关键配置点

SecurityConfig 中关注以下关键设置:

  • 通过 csrf().disable() 禁用 CSRF 保护。
  • 使用 authenticationEntryPoint(unauthorizedHandler) 设置未授权处理。
  • 启用非会话模式,数组的用户不会创建 session。
  • 使用 permitAll() 允许匿名访问的路径。
  • 使用 frameOptions().disable() 禁用同源策略,允许跨域请求。
  • 启用 JWT 过滤器,确保每个请求都包含有效 Token。
  • 备注

    本配置类主要用于控制访问权限。常用的路径包括登录页面和静态资源,这些路径一般使用 permitAll() 设置为匿名访问,以提升用户体验。其他所有请求默认需要授权。

    记住,以上配置仅供测试参考,在实际应用中建议添加 Token 验证中间件(如 JWT наруш者)和权限控制模块,确保系统安全性。

    上一篇:asp.net core 比较好的开源项目
    下一篇:学生成绩管理系统-设计文档

    发表评论

    最新留言

    表示我来过!
    [***.240.166.169]2025年04月23日 09时42分12秒