[英]Spring boot + OAuth2 security & request filter
我已经用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 {
}
}
让我知道此安全配置中出了什么问题。
您需要从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)//
如果您的过滤器出现任何异常,它将被调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.