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

时间:2019-03-25 20:22:39

标签: spring spring-security oauth-2.0

我想使用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 {

@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) -> {});
    }

3 个答案:

答案 0 :(得分:1)

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

@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");
    }
}

答案 1 :(得分:0)

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

因此在您的安全配置中

http
 .authorizeRequests()
    .antMatchers("/noauth").permitAll()
  .oauth2Login()
    .loginPage("/noauth")

在控制器中

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

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

答案 2 :(得分:0)

我想扩展 Petr 的回答,首先解释一下,当有多个 OAuth2 配置的提供程序时,会显示默认登录页面。我希望 Spring Boot 有一个聪明的技巧可以轻松绕过此页面并自动选择正确的提供程序,例如基于关于原始请求中提供者的客户端 ID 的存在。我发现事实并非如此。所以这样做的方法是.. 为失败提供自定义处理程序的这种不太明显的技巧 - 根据原始 HTTP 请求 URL,它将用户重定向到每个提供程序的正确 OAuth2 端点。我尝试了这个并且它有效,我花了一整天的时间尝试其他解决方案的所有方式 - 我最初的场景是将额外的参数传递给 OAuth2 方案,以便能够让它们重新获得成功的身份验证 - 他们曾经这样做附加 Base64将信息编码到“状态”URL 请求参数,但 Spring Security 目前不允许这样做。因此,唯一的替代方法是使用已经存在的这些参数调用受 Spring Security 保护的 URL,因此当成功进行身份验证时,会自动再次访问该 URL,并保留这些参数。

相关:Multiple Login endpoints Spring Security OAuth2