首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring boot + OAuth2安全和请求过滤器

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

Stack Overflow用户
提问于 2019-08-13 12:58:11
回答 1查看 899关注 0票数 0

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

在内部,如果发生任何异常,/error都会被重定向&这不需要通过OAuth2AuthenticationProcessingFilter,可以跳过这个请求。

代码语言:javascript
运行
复制
http.authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();
   // both configuration validates even "ERROR" request.
http.antMatcher("/**").authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();
代码语言:javascript
运行
复制
// security config with filter 
    http.addFilterBefore(new APISignatureFilter(), OAuth2AuthenticationProcessingFilter.class).authorizeRequests().antMatchers("/error").permitAll().anyRequest().authenticated();

我已经实现了OncePerRequestFilter &任何请求都不会调用它。这必须在OAuth筛选器之前调用。

代码语言:javascript
运行
复制
@Component
public class APISignatureFilter extends OncePerRequestFilter {

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-08-13 14:04:57

您需要实现spring security中的AuthenticationEntryPoint接口。

代码语言:javascript
运行
复制
 @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安全配置中定义这个入口点,如下所示

代码语言:javascript
运行
复制
         http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(//bean of 
           JwtAuthenticationEntryPoint)//

如果您的筛选器中出现任何异常,将调用此函数

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57471351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档