我已经使用OAuth2实现了基于Spring boot的REST API来进行身份验证。我必须使用OAuth2AuthenticationProcessingFilter
验证所有请求,以检查授权标头令牌载体并验证它。此外,在使用OAuth过滤器验证请求之前,我需要为“所有”请求自定义过滤器,以检查一些强制性的请求头参数。
在内部,如果发生任何异常,/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 {
}
}
让我知道这个安全配置出了什么问题。
发布于 2019-08-13 14:04:57
您需要实现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)//
如果您的筛选器中出现任何异常,将调用此函数
https://stackoverflow.com/questions/57471351
复制相似问题