由于篇幅所限,下面仅展示如何使用Spring Security配置JWT认证和权限控制的核心代码片段。
Spring Security配置类(部分)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 禁用CSRF
.csrf().disable()
// 不通过Session进行认证
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// 配置认证URL的访问权限
.authorizeRequests()
// 允许对登录URL进行匿名访问
.antMatchers("/auth/login").permitAll()
// 其他所有请求都需要认证
.anyRequest().authenticated();
// 添加JWT认证过滤器
httpSecurity
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 处理异常情况
httpSecurity
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
}
// 其他配置略...
}
JWT过滤器
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletReques