首页 > 解决方案 > Spring Security:oauth2Login 仅在某些路径上重定向

问题描述

我已将 Spring Security 配置为对我的网站进行身份验证,这样所有路径都会自动重定向到 OAuth2 授权 URL(使用.oauth2Login())。但是,我希望对 API(即/api/**)的未经身份验证的请求返回401 Unauthorized而不是被重定向。我不知道该怎么做。任何帮助将非常感激。

这是我当前的配置:

http
    .authorizeRequests()
    .antMatchers("/api/auth/oauth2/callback").permitAll()
    .anyRequest().authenticated()
    .oauth2Login()
    .authorizationEndpoint()
    .baseUri(this.oauth2AuthorizationRedirectBaseUri);

http.logout()
    .logoutUrl("/auth/logout")
    .invalidateHttpSession(true)
    .deleteCookies("JSESSIONID");

标签: spring-bootspring-securityspring-security-oauth2

解决方案


您可以为 /API/** 定义自定义身份验证入口点并将 t 添加到您的配置中:

@Component
public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
      throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

@Override
public void afterPropertiesSet() throws Exception {
    setRealmName("developers");
    super.afterPropertiesSet();
}

}

在您的 Http 安全配置中添加:

 http.
     ...
     .exceptionHandling()
     .defaultAuthenticationEntryPointFor(
              new CustomAuthenticationEntryPoint(),
              new AntPathRequestMatcher("/api/**"))

推荐阅读