Spring Boot 3 JWT 安全性项目指南
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;
import org.springframework.beans.factory.annotation.Autowired;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 禁用 CSRF (跨站请求伪造)
.csrf().disable()
// 不通过Session进行认证
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// 配置JWT认证入口
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
// 配置基于token的身份验证方式
.authorizeRequests()
// 对于GET, POST, PUT, DELETE请求,需要认证
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/user/me").permitAll()
.antMatchers("/api/user/checkEmail").permitAll()
.anyRequest().authenticated();
// 添加JWT filter
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
这个代码示例展示了如何在Spring Boot 3项目中配置HttpSecurity来使用JW
评论已关闭