Spring Security OAuth - 如何禁用登录页面?

nag*_*hun 4 spring spring-security oauth-2.0

我想使用 OAuth 2 通过 Spring Security 保护我的应用程序。但是,我不希望服务器重定向传入的未经授权的请求,而是使用 HTTP 401 进行响应。这可能吗?

示例:此代码将请求重定向到默认登录页面。

应用程序属性

spring.security.oauth2.client.registration.google.client-id=...
spring.security.oauth2.client.registration.google.client-secret=...
Run Code Online (Sandbox Code Playgroud)

验证配置文件

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/secured/**").authenticated()
            .anyRequest().permitAll()
            .and()
            .oauth2Login();


        // /sf/ask/2220020981/
        // deos not work
        // .and()
        // .formLogin().successHandler((request, response, authentication) -> {});
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您需要创建新的身份验证入口点并在配置中进行设置。

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)


den*_*nov 3

你需要设置oauth2Login.loginPageHttpSecurity配置中进行设置并创建控制器映射以返回您想要的任何内容。这是一个简单的例子。

所以在你的安全配置中

http
 .authorizeRequests()
    .antMatchers("/noauth").permitAll()
  .oauth2Login()
    .loginPage("/noauth")
Run Code Online (Sandbox Code Playgroud)

在控制器中

@GetMapping("/noauth")
public ResponseEntity<?> noAuth() {
    Map<String, String> body = new HashMap<>();
    body.put("message", "unauthorized");
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
Run Code Online (Sandbox Code Playgroud)

您可以将地图或 pojo 传递给该body方法。