添加安全过滤器后 Rest API 不返回结果

问题描述 投票:0回答:0

我有一个 POST Rest 端点,它在成功执行后返回一个字符串列表。最近我尝试使用 Spring Security 来保护它。没什么疯狂的,我尝试了简单的实现,它检查提供的 Bearer 令牌是否不为 null 并确保它以“Bearer”开头。

这是我的 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 {

        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 {

        final String requestTokenHeader = request.getHeader("Authorization");
        String jwtToken = null;
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            Logger.info("Token Value: ", jwtToken);
        } else {
            Logger.warn("Invalid Token");
            chain.doFilter(request, response);
        }
    }
}
  

当我访问提供空令牌的 Rest API(通过邮递员)时,它会按预期返回 401 UnAuthorized。但是当我通过提供有效的 Bearer 令牌访问它时(出于安全原因未在此处提供),它返回 200 ok http 状态,但邮递员正文中的响应为空(预期响应是字符串列表)。我在想的是,在 SecurityConfig 中处理过滤器(httpSecurity.addFilterBefore)后,控件不会返回到 Rest Controller API。有没有办法来解决这个问题?我将 POST 更改为 GET,但我仍然看到问题。

java spring-boot spring-security spring-security-oauth2 spring-security-rest
© www.soinside.com 2019 - 2024. All rights reserved.