我已将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");
你可以为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/**"))