我已经实现了基于 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/