java - Spring boot + OAuth2 安全和请求过滤器

标签 java spring spring-boot spring-security

我已经实现了基于 Spring boot 的 REST API,并使用 OAuth2 进行身份验证。我必须使用 OAuth2AuthenticationProcessingFilter 来验证所有请求,以检查授权 header token 持有者并验证它。另外,在使用 OAuth 过滤器验证请求之前,我需要为“ALL”请求设置自定义过滤器来检查一些强制请求 header 参数。

在内部,如果发生任何异常,/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 {
    }
 }

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

最佳答案

您需要从 Spring Security 实现 AuthenticationEntryPoint 接口(interface)

 @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)//

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

关于java - Spring boot + OAuth2 安全和请求过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471351/

相关文章:

java - 使用 ChromeDriver 设置 browsermob 代理

java - 在使用 Helidon Microprofile Server 时,我们可以使用 Spring 代替 CDI 和 Weld 吗?

java - MongoDB-Java : Not operator and regular expressions

java - 无法从 openapi 客户端中的字符串反序列化 `java.time.OffsetDateTime` 类型的值

java - 微服务 - 如何使用授权服务器和资源服务器对注册流程进行建模?

java - 如果不使用方法名称生成查询,Spring Data 的好处是什么?

java - 应用程序适用于 API 26,但在 API 23(棉花糖)上崩溃

java - java中如何使用Lock指定要锁定的对象

java - 除了构造函数重载java之外的最佳实践/设计模式

java - 如何在 Spring 框架中将多个输入存储到数组中