Spring Boot + OAuth2安全和请求过滤器

时间:2019-08-13 04:58:11

标签: java spring spring-boot spring-security

我已经使用OAuth2实现了基于Spring Boot的REST API进行身份验证。我必须使用OAuth2AuthenticationProcessingFilter验证所有请求,以检查Authorization标头令牌承载并进行验证。另外,在使用OAuth过滤器验证请求之前,我需要对“ ALL”请求具有自定义过滤器,以检查一些强制性请求标头参数。

在内部,如果发生任何/error异常,并且不需要通过OAuth2AuthenticationProcessingFilter,则可以跳过此请求。

http.authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();
   // both configuration validates even "ERROR" request.
http.antMatcher("/**").authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();
// security config with filter 
    http.addFilterBefore(new APISignatureFilter(), OAuth2AuthenticationProcessingFilter.class).authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();

我已经实现了OncePerRequestFilter,并且没有为任何请求调用它。必须在OAuth过滤器之前调用它。

@Component
public class APISignatureFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    }
 }

让我知道此安全配置中出了什么问题。

1 个答案:

答案 0 :(得分:0)

您需要从Spring Security中实现AuthenticationEntryPoint接口

 @Component
 public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
 private static final Logger logger = 
 LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest,
                     HttpServletResponse httpServletResponse,
                     AuthenticationException e) throws IOException, ServletException 
{
    logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
            "Sorry, You're not authorized to access this resource.");
} 
}

,您需要在

之类的spring安全配置中定义此入口点
         http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(//bean of 
           JwtAuthenticationEntryPoint)//

如果您的过滤器出现任何异常,它将被调用