我想使用 OAuth 2 通过 Spring Security 保护我的应用程序。但是,我不希望服务器重定向传入的未授权请求,而是使用 HTTP 401 进行响应。这可能吗?
示例:此代码将请求重定向到默认登录页面。
应用程序属性
spring.security.oauth2.client.registration.google.client-id=...
spring.security.oauth2.client.registration.google.client-secret=...
验证配置文件
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
.and()
.oauth2Login();
// https://stackoverflow.com/questions/31714585/spring-security-disable-login-page-redirect
// deos not work
// .and()
// .formLogin().successHandler((request, response, authentication) -> {});
}
}
最佳答案
您需要创建新的身份验证入口点并在配置中进行设置。
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
.and()
.oauth2Login();
}
}
public class AuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public AuthenticationEntryPoint() {
super("");
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendError(401, "Unauthorized");
}
}
关于Spring Security OAuth - 如何禁用登录页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345833/