
[英]Can I have two Spring Security configuration classes: one that protect some API with basic authentication and another protecting APIs with JWT token?
[英]API requires JWT Token on all requests despite the authentication configuration
我正在尝试按照本教程(本教程的后续教程)为我的 API 实施 JWT 授权。当我尝试使用“/authenticate”和“/register”时,出现错误“JWT Token does not从 Bearer String 开始”。
这是抛出错误的请求过滤器的一部分:
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
}
这是应该允许“验证”和“请求”请求通过的 websecurityconfig。 我有点困惑,因为我找不到教程中实际调用它的位置:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private UserDetailsService jwtUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate", "/register").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
附件是 github 的链接。
https://github.com/Dikianify/ReporterAPI.git
谢谢
因为 jwtRequestFilter 是一个过滤器,它将在每个请求(包括 /authenticate 和 /register)上调用,而不仅仅是那些需要身份验证的请求。
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
这不是问题,因为代码只是将警告写入日志并将请求向下传递以进行进一步处理。
logger.warn("JWT Token does not begin with Bearer String");
当用户通过身份验证后,带有令牌的 Bearer header 应该在过滤器提取用户名的每个请求中通过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.