我想使用OAuth 2使用Spring Security保护我的应用程序。但是,我不希望服务器重定向传入的未授权请求,而是使用HTTP 401进行响应。可以吗?
示例:此代码将请求重定向到默认登录页面。
application.properties
spring.security.oauth2.client.registration.google.client-id=...
spring.security.oauth2.client.registration.google.client-secret=...
AuthConfig.java
@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) -> {});
}
}
您需要在oauth2Login.loginPage
配置中设置oauth2Login.loginPage
并创建一个控制器映射以返回您想要的任何内容。这是一个简单的示例。
因此在您的安全配置中
HttpSecurity
在控制器中
http
.authorizeRequests()
.antMatchers("/noauth").permitAll()
.oauth2Login()
.loginPage("/noauth")
您可以将地图或pojo传递给@GetMapping("/noauth")
public ResponseEntity<?> noAuth() {
Map<String, String> body = new HashMap<>();
body.put("message", "unauthorized");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
方法。