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

Vaadin与Spring Security集成的安全配置及自定义登录相关问题咨询

自定义Servlet登录表单适配方案

你只需要修改Spring Security的SecurityFilterChain配置,指定自定义登录页路径同时保留Vaadin原有权限校验逻辑即可,示例配置如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends VaadinWebSecurity {

    @Bean
    @Override
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 放行自定义登录表单端点
        http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/my-login-form").permitAll());

        // 保留Vaadin原有权限校验逻辑
        super.filterChain(http);

        // 覆盖默认登录配置
        http.formLogin(form -> form
            .loginPage("/my-login-form")
            .defaultSuccessUrl("/", true)
            .failureUrl("/my-login-form?error")
            .permitAll()
        );

        http.logout(logout -> logout
            .logoutSuccessUrl("/my-login-form?logout"));

        return http.build();
    }
}

注意事项:

  • 你的纯HTML表单提交地址默认要为/login,参数名对应username和password,如果有自定义提交路径或参数名,可以在formLogin配置中通过loginProcessingUrl、usernameParameter、passwordParameter单独指定
  • Vaadin原有的@PermitAll、@RolesAllowed等路由权限注解不需要修改,会正常生效

测试环境免登录配置方案

可以通过Spring Profile实现多环境配置,不需要移除Spring Security依赖,示例如下:

// 正式环境配置,非test profile时生效
@Configuration
@EnableWebSecurity
@Profile("!test")
public class ProductionSecurityConfig extends VaadinWebSecurity {
    // 写入上面的正式环境配置内容
}

// 测试环境配置,test profile时生效
@Configuration
@EnableWebSecurity
@Profile("test")
public class TestSecurityConfig {
    @Bean
    public SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .csrf(csrf -> csrf.disable());
        return http.build();
    }

    // 可选:如果业务代码依赖用户信息上下文,可配置默认测试用户
    @Bean
    public UserDetailsService testUser() {
        return new InMemoryUserDetailsManager(
            User.withUsername("test")
                .password("{noop}123456")
                .roles("USER", "ADMIN")
                .build()
        );
    }
}

使用时只需要在测试配置中激活test profile,或者在本地调试时在application.properties中添加spring.profiles.active=test,即可绕过登录直接访问所有路由。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:02