Spring Boot Security 整合 JWT 实现 无状态的分布式API接口
以下是一个简化的Spring Boot Security和JWT整合的示例代码,用于实现无状态的分布式API接口:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// 配置自定义的用户DetailsService,用于加载用户详情
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated();
// 添加JWT filter
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public AuthenticationJwtTokenFilter authenticationJwtTokenFilter() {
return new AuthenticationJwtTokenFilter();
}
}
@Component
public class AuthenticationJwtTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// 获取token,如果存在,则进行解析和验证
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String token = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
token = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(token);
} catch (IllegalArgumentException e) {
// 如果解析失败,则会抛出异常,我们会直接返回401状态码
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// 如果token存在,则从数据库中获取用户信息并验证
UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(token, userDetails)) {
UsernamePasswordAu
评论已关闭