You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用Spring Security OAuth2(Keycloak)默认登录页面

问题描述

我已经成功完成Spring Boot、Spring Security与Keycloak的集成配置,所有功能运行正常,当前通过URL:http://localhost:8081/realms/MY_REALM_NAME 执行登录操作。但访问http://localhost:8080/login时,会显示默认登录页面,希望禁用该页面,请问如何通过Spring Security进行正确配置?

更新内容
我的Spring Security配置代码如下:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {

    private final ClientRegistrationRepository clientRegistrationRepository;
    private final GrantedAuthoritiesMapper authoritiesMapper;
    private final ProfileService profileService;

    SecurityConfiguration(ClientRegistrationRepository clientRegistrationRepository,
                          GrantedAuthoritiesMapper authoritiesMapper, ProfileService profileService) {
        this.clientRegistrationRepository = clientRegistrationRepository;
        this.authoritiesMapper = authoritiesMapper;
        this.profileService = profileService;
        SecurityContextHolder.setStrategyName(VaadinAwareSecurityContextHolderStrategy.class.getName());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                // Enable OAuth2 login
                .oauth2Login(oauth2Login ->
                        oauth2Login
                                .clientRegistrationRepository(clientRegistrationRepository)
                                .userInfoEndpoint(userInfoEndpoint ->
                                        userInfoEndpoint
                                                // Use a custom authorities mapper to get the roles from the identity provider into the Authentication token
                                                .userAuthoritiesMapper(authoritiesMapper)
                                )
                                // Use a Vaadin aware authentication success handler
                                .successHandler(new KeycloakVaadinAuthenticationSuccessHandler(profileService))
                )
                // Configure logout
                .logout(logout ->
                        logout
                                // Enable OIDC logout (requires that we use the 'openid' scope when authenticating)
                                .logoutSuccessHandler(logoutSuccessHandler())
                                // When CSRF is enabled, the logout URL normally requires a POST request with the CSRF
                                // token attached. This makes it difficult to perform a logout from within a Vaadin
                                // application (since Vaadin uses its own CSRF tokens). By changing the logout endpoint
                                // to accept GET requests, we can redirect to the logout URL from within Vaadin.
                                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                );
    }

    @Bean
    @Primary
    public SpringViewAccessChecker springViewAccessChecker(AccessAnnotationChecker accessAnnotationChecker) {
        return new KeycloakSpringViewAccessChecker(accessAnnotationChecker, "/oauth2/authorization/keycloak");
    }

    private OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler() {
        var logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
        logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
        return logoutSuccessHandler;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        // Don't apply security rules on our static pages
        web.ignoring().antMatchers("/session-expired");
    }

    @Bean
    public PolicyFactory htmlSanitizer() {
        // This is the policy we will be using to sanitize HTML input
        return Sanitizers.FORMATTING.and(Sanitizers.BLOCKS).and(Sanitizers.STYLES).and(Sanitizers.LINKS);
    }

}
解决方案

要禁用Spring Security的默认登录页面,可通过以下方式修改配置:

核心方案:关闭默认表单登录并确保OAuth2登录流程主导

在configure(HttpSecurity http)方法中,添加formLogin().disable()关闭Spring Security自带的表单登录机制,同时保留OAuth2登录的完整配置。这样访问/login时会直接触发Keycloak的授权流程,而非显示默认页面:

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http
            // 关闭默认表单登录,禁用默认登录页
            .formLogin(formLogin -> formLogin.disable())
            // 保留原有OAuth2登录配置
            .oauth2Login(oauth2Login ->
                    oauth2Login
                            .clientRegistrationRepository(clientRegistrationRepository)
                            .userInfoEndpoint(userInfoEndpoint ->
                                    userInfoEndpoint
                                            .userAuthoritiesMapper(authoritiesMapper)
                            )
                            .successHandler(new KeycloakVaadinAuthenticationSuccessHandler(profileService))
            )
            // 保留原有登出配置
            .logout(logout ->
                    logout
                            .logoutSuccessHandler(logoutSuccessHandler())
                            .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
            );
}

补充:直接限制/login端点访问(可选)

如果需要彻底禁止外部访问/login端点,可在configure(WebSecurity web)中添加忽略规则:

@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
    web.ignoring().antMatchers("/session-expired");
    // 禁止访问/login端点
    web.ignoring().antMatchers("/login");
}

注意:此方式仅适合已确保所有登录请求都会通过Vaadin视图的访问控制触发Keycloak授权的场景,否则可能导致未认证请求无法正常跳转登录。

另外,你已配置的KeycloakSpringViewAccessChecker指定了正确的授权入口/oauth2/authorization/keycloak,这会确保Vaadin视图的权限控制直接导向Keycloak登录,无需依赖默认的/login页面。

内容的提问来源于stack exchange,提问作者alexanoid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:56:07