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

标签 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=...

验证配置文件
@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/

相关文章:

java - 使用 JMS 监听器自动刷新 Wicket 组件

c# - 如何在 ASP.NET Core 中为 Azure AD 请求正确的访问 token 来访问 Microsoft Graph

spring - Spring WebFlux 支持 OAuth2 授权服务器吗?

java - 如何使用 JPA 和 Spring 在列表中查找具有字段的不同行?

java - 如何使用对象有效负载而不是来自 MessageCollector 的字符串接收 GenericMessage

java - 我如何告诉 spring security 只为特定端口应用 authorizeRequests?

hibernate - 无法使用从同一 Maven 原型(prototype)创建的两个 SpringMVC Web 应用程序启动 Tomcat 服务器

ios - 带有 iOS 的 Google App Engine 上的 Facebook OAuth

java - 同一接口(interface)的Spring多重实现

java - 使用相同的 URL 登录并检索数据