如何使用 vaadin14 正确配置 spring-security 以处理 2 个入口点 - keyclaok 和 DB

如何解决如何使用 vaadin14 正确配置 spring-security 以处理 2 个入口点 - keyclaok 和 DB

我有一个 vaadin14 应用程序,我想在不同的 url 路径上启用不同类型的身份验证机制。一个是test url,其中认证应该使用DB,另一个是使用keycloak的生产url。

我能够让每种身份验证机制单独工作,但是一旦我尝试同时使用这两种机制,就会得到意想不到的结果。

在这两种情况下,我都获得了登录页面,但身份验证无法正常工作。这是我的安全配置,我做错了什么?

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration {


  @Configuration
  @Order(2)
  public static class DBAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {


    private static final String LOGIN_PROCESSING_URL = "/login";
    private static final String LOGIN_FAILURE_URL = "/login?error";
    private static final String LOGIN_URL = "/login";
    private static final String LOGOUT_SUCCESS_URL = "/login";

    /**
     * Require login to access internal pages and configure login form.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

      // Not using Spring CSRF here to be able to use plain HTML for the login page
      http.csrf().disable()

        // Register our CustomRequestCache,that saves unauthorized access attempts,so
        // the user is redirected after login.
        .requestCache().requestCache(new CustomRequestCache())

        // Restrict access to our application.
        .and().antMatcher("/test**").authorizeRequests()

        // Allow all flow internal requests.
        .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()

        // Allow all requests by logged in users.
        .anyRequest().hasRole("USER")

        // Configure the login page.
        .and().formLogin().loginPage(LOGIN_URL).permitAll().loginProcessingUrl(LOGIN_PROCESSING_URL)
        .failureUrl(LOGIN_FAILURE_URL)

        // Configure logout
        .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {

      Properties users = null;
      try {
        users = PropertiesLoaderUtils.loadAllProperties("users.properties");
        return new InMemoryUserDetailsManager(users);
      } catch (IOException e) {
        e.printStackTrace();
      }

      UserDetails user =
        User.withUsername("user")
        .password("{noop}password")
        .roles("ACTOR")
        .build();

      return new InMemoryUserDetailsManager(user);
    }

    /**
     * Allows access to static resources,bypassing Spring security.
     */
    @Override
    public void configure(WebSecurity web) {
      web.ignoring().antMatchers(
        // Vaadin Flow static resources
        "/VAADIN/**",// the standard favicon URI
        "/favicon.ico",// the robots exclusion standard
        "/robots.txt",// web application manifest
        "/manifest.webmanifest","/sw.js","/offline-page.html",// icons and images
        "/icons/**","/images/**",// (development mode) static resources
        "/frontend/**",// (development mode) webjars
        "/webjars/**",// (development mode) H2 debugging console
        "/h2-console/**",// (production mode) static resources
        "/frontend-es5/**","/frontend-es6/**","/resources/**");
    }
  }

  @Order(1)
  @Configuration
  @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
  public static class AppKeycloakSecurity extends KeycloakWebSecurityConfigurerAdapter {


    @Autowired
    public void configureGlobal(
      AuthenticationManagerBuilder auth) throws Exception {

      KeycloakAuthenticationProvider keycloakAuthenticationProvider
        = keycloakAuthenticationProvider();
      keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
        new SimpleAuthorityMapper());
      auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
      return new KeycloakSpringBootConfigResolver();
    }


    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
      return new RegisterSessionAuthenticationStrategy(
        new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      super.configure(http);

      http.httpBasic().disable();
      http.formLogin().disable();
      http.anonymous().disable();
      http.csrf().disable();
      http.headers().frameOptions().disable();

      http
        .antMatcher("/prod**")
        .authorizeRequests()
        .antMatchers("/vaadinServlet/UIDL/**").permitAll()
        .antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
        .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
        .anyRequest().hasRole("actor");

      http
        .logout()
        .addLogoutHandler(keycloakLogoutHandler())
        .logoutUrl("/logout").permitAll()
        .logoutSuccessUrl("/");
      http
        .addFilterBefore(keycloakPreAuthActionsFilter(),LogoutFilter.class);
      http
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint());
      http
        .sessionManagement()
        .sessionAuthenticationStrategy(sessionAuthenticationStrategy());
    }
  }

}

解决方法

在 Vaadin UI 中导航将更改浏览器中的 URL,但它不一定会创建对该确切 URL 的浏览器请求,从而有效地绕过 Spring 安全为该 URL 定义的访问控制。因此,Vaadin 真的不适合 Spring 提供的基于请求 URL 的安全方法。仅针对这个问题,您可以查看我的附加组件 Spring Boot Security for Vaadin,我专门创建它来缩小 Spring 安全性和 Vaadin 之间的差距。

但是,虽然基于 URL 创建两个不同的 Spring 安全上下文相当容易,但出于同样的原因,这对 Vaadin 不起作用或根本不起作用。这甚至是我的附加组件也无法解决的问题。

更新:由于您可以选择结合两种安全上下文,我可以提供以下解决方案(使用我的附加组件): 从 Keycloak example 开始,您必须执行以下操作:

  1. 更改 WebSecurityConfig 以添加基于数据库的 AuthenticationProvider。添加您的 UserDetailsService 应该仍然足够。确保为每个用户分配合适的角色。
  2. 您必须从 application.properties 中删除此行:codecamp.vaadin.security.standard-auth.enabled = false 这将通过 Vaadin 视图重新启用没有 Keycloak 的标准登录。
  3. 调整 KeycloakRouteAccessDeniedHandler 以忽略不应受 Keycloak 保护的所有测试视图。

我已经 prepared all this in Gitlab repo 并删除了对于此解决方案的要点不重要的所有内容。查看各个提交及其差异,以帮助您专注于重要的部分。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-