我已将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");
答案 0 :(得分:0)
您可以为/ 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/**"))