我有一个POST Rest端点,它在成功执行时返回字符串列表。最近我尝试使用Spring Security来保护它。没有什么疯狂的,我尝试了简单的实现,检查提供的承载令牌是否不为空。
这是我的SecurityConfig类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/home").permitAll()
.anyRequest().authenticated().and()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, BasicAuthenticationFilter.class);
}
}
这是我的JwtAuthenticationEntryPoint类:@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint,
Serializable {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
String token = request.getHeader("Authorization");
if (token == null) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
}
下面是过滤器类:
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
}
}
当我访问Rest API(通过邮递员)提供一个空令牌,它返回401未授权的预期。但是,当我通过提供有效的承载令牌(出于安全原因不在这里提供)访问它时,它返回200 ok http状态,但在邮递员体中响应为空(期望的响应是字符串列表)。我想的是,在SecurityConfig中处理过滤器(httpSecurity.addFilterBefore)后,控件不会返回到Rest控制器API。有办法解决这个问题吗?我把POST改为GET,我仍然看到问题。
JwtRequestFilter的doFilterInternal方法类,对chain.doFilter(request, response)
的调用应处于if条件。
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
Logger.info("Token Value: " + jwtToken);
chain.doFilter(request, response);
}
else块应该包含无效令牌的逻辑。
else {
Logger.warn("Invalid Token");
// code to send invalid token message to the user
}