我正在使用带有JWT的Spring Security来验证Rest API。登录时,将生成JWT令牌并将其共享给移动客户端。但是,后续请求中的令牌未得到验证。安全配置有什么问题吗?
Spring安全版本-5.1.6.RELEASE
//安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.
httpBasic().disable().
csrf().disable().
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
and().
addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().
authorizeRequests().antMatchers("/user/login").permitAll().
antMatchers("/user/test").authenticated().
anyRequest().authenticated();
}
}
// JWT令牌验证过滤器-永远不会调用
@Component
public class JwtTokenAuthenticationFilter extends GenericFilterBean {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
String token = jwtTokenProvider.resolveToken((HttpServletRequest) req);
if (null != token && jwtTokenProvider.validateToken(token)) {
Authentication auth = jwtTokenProvider.getAuthentication(token);
if (null != auth) {
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
filterChain.doFilter(req, res);
}
}
我期望登录后的所有请求都将根据JWT令牌进行身份验证。 我尝试将服务名称进行身份验证,如下所示:
antMatchers("/user/test").authenticated().
此外,还添加了任何经过身份验证的请求,但是它们都不起作用。
anyRequest().authenticated();
答案 0 :(得分:0)
尝试更换
addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).
通过
addFilterBefore(jwtTokenAuthenticationFilter), BasicAuthenticationFilter.class);
如果未运行,请更改jwtTokenAuthenticationFilter类以避免成为Spring bean并按以下方式使用:
addFilterBefore(new JwtTokenAuthenticationFilter(jwtTokenProvider)), BasicAuthenticationFilter.class);
并在安全类上添加以下代码:
@Autowired
private JwtTokenProvider jwtTokenProvider;