当前位置: 首页 > 知识库问答 >
问题:

SpringBoot多重身份验证适配器

陈高寒
2023-03-14

我在Spring Boot web应用程序中有一个非常特殊的要求:我有内部和外部用户。内部用户通过使用KeyCoap身份验证登录到web应用程序(他们可以在web应用程序中工作),但我们的外部用户通过简单的Spring Boot身份验证登录(他们可以做的只是下载web应用程序生成的一些文件)

我想做的是使用多个身份验证模型:除了/download/*之外的所有路径都要通过我们的keyCoap身份验证,但路径/downlood/*要通过SpringBoot基本身份验证。

目前我有以下几点:

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {

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

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(keycloakAuthenticationProvider());
        }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            http
                .regexMatcher("^(?!.*/download/export/test)")
                .authorizeRequests()
                .anyRequest().hasAnyRole("ADMIN", "SUPER_ADMIN")
                .and()
                .logout().logoutSuccessUrl("/bye");
        }

    }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/download/export/test")
                .authorizeRequests()
                .anyRequest().hasRole("USER1")
                .and()
                .httpBasic();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password1").roles("USER1");
        }

    }
}

但是它并不能很好地工作,因为每次外部用户想要下载一些东西(/下载/导出/测试)时,它都会提示登录表单,但是在输入正确的外部用户用户名和密码后,它会提示密钥斗篷认证登录表单。

我没有收到任何错误,只是一个警告:

2016-06-20 16:31:28.771  WARN 6872 --- [nio-8087-exec-6] o.k.a.s.token.SpringSecurityTokenStore   : Expected a KeycloakAuthenticationToken, but found org.springframework.security.authentication.UsernamePasswordAuthenticationToken@3fb541cc: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER1; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: 4C1BD3EA1FD7F50477548DEC4B5B5162; Granted Authorities: ROLE_USER1

你有什么想法吗?

共有2个答案

华宏逸
2023-03-14

多重HttpSecurity的关键是在正常情况之前注册“特例”。换句话说,< code >/download/export/test 身份验证适配器应该在keycloak适配器之前注册。

需要注意的另一件重要事情是,一旦身份验证成功,就不会调用其他适配器(因此不需要<code>.regexMatcher(^(?)*/download/export/test))。有关多个HttpSecurity的更多信息,请参见此处。

下面的代码只需稍加修改:

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {

    @Configuration
    @Order(1) //Order is 1 -> First the special case
    public static class DownloadableExportFilesSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/download/export/test")
                    .authorizeRequests()
                    .anyRequest().hasRole("USER1")
                .and()
                    .httpBasic();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password1").roles("USER1");
        }

    }

    @Configuration
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
    @Order(2) //Order is 2 -> All other urls should go through the keycloak adapter
    public static class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(keycloakAuthenticationProvider());
        }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            http
                //removed .regexMatcher("^(?!.*/download/export/test)")
                .authorizeRequests()
                    .anyRequest().hasAnyRole("ADMIN", "SUPER_ADMIN")
                .and()
                    .logout().logoutSuccessUrl("/bye");
        }

    }
}
艾泰
2023-03-14

在 Keycloak 身份验证旁边实现基本身份验证时,我遇到了一些麻烦,因为在“按书”执行多个 WebSecurityAdapter 实现时,即使基本身份验证成功,也会调用 Keycloak 身份验证筛选器。

原因在于:http://www.keycloak.org/docs/latest/securing_apps/index.html#avoid-双过滤器bean注册

因此,如果您将Keycloak Spring Security Adapter与Spring Boot一起使用,请确保添加这两个bean(除了Jacob von Lingen的有效答案):

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {

    @Configuration
    @Order(1) //Order is 1 -> First the special case
    public static class DownloadableExportFilesSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception 
        {
            http
                .antMatcher("/download/export/test")
                    .authorizeRequests()
                    .anyRequest().hasRole("USER1")
                .and()
                    .httpBasic();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
              .withUser("user").password("password1").roles("USER1");
        }

    }

    @Configuration
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
    //no Order, will be configured last => All other urls should go through the keycloak adapter
    public static class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

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

       auth.authenticationProvider(keycloakAuthenticationProvider());
        }

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

        // necessary due to http://www.keycloak.org/docs/latest/securing_apps/index.html#avoid-double-filter-bean-registration
        @Bean
        public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter filter) {
            FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
            registrationBean.setEnabled(false);
            return registrationBean;
        }
        // necessary due to http://www.keycloak.org/docs/latest/securing_apps/index.html#avoid-double-filter-bean-registration
        @Bean
        public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(KeycloakPreAuthActionsFilter filter) {
            FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
            registrationBean.setEnabled(false);
            return registrationBean;
        }


        @Override
        protected void configure(HttpSecurity http) throws Exception 
        {
            super.configure(http);
            http
                .authorizeRequests()
                .anyRequest().hasAnyRole("ADMIN", "SUPER_ADMIN")
                .and()
                .logout().logoutSuccessUrl("/bye");
        }

    }
}
 类似资料:
  • 我正在laravel中创建一个多身份验证系统,其中有两种类型的用户:管理员(由我创建)和用户(使用本地laravel身份验证系统)。 如果我以用户身份登录,当我尝试访问登录页面时,当我已经登录,它会将我重定向回仪表板,但如果我以管理员身份登录,当我再次访问管理员登录页面时,它会让我再次登录,尽管已经作为管理员登录。 以下是我的重定向身份验证类代码: 有人能解释一下发生了什么事吗?

  • 我的管理员控制器扩展了控制器类,在那里我使用方法加载视图页面并传递保护。config/auth.php也通过添加管理员保护和提供程序进行了修改。在app/Actions/Fortify文件夹中,我添加了AttemptToAuthenticate和ReDirectIfTwoFactorAuthenticate类,并更改了命名空间。我的管理员控制器还扩展了Guard。用户的重定向中间件和管理员的重定向

  • 在我的LaravelV5.4项目中,我有两个模型:用户和管理员。 在config/auth.php中,我向警卫和提供者添加了admin,如下所示: 现在在AdminController类中,我想使用Auth::true函数,但默认情况下它使用用户表。我可以在config/auth.php中更改默认值,如下所示,它可以工作,但在这种情况下,我不能为用户使用auth::trunt。 我想将用户设置为默

  • 我正在使用SpringBoot开发具有微服务架构的Rest Backend。为了保护endpoint,我使用了JWT令牌机制。我正在使用Zuul API网关。 如果请求需要权限(来自JWT的角色),它将被转发到正确的微服务。Zuul api网关的“WebSecurityConfigrerAdapter”如下。 这样,我必须在这个类中编写每个请求授权部分。因此,我希望使用方法级安全性,即“Enabl

  • 我正在进行多重身份验证。我的前端有一个带有卡号和密码的登录表单。在auth.php中 在route.php中 在logincontroller中, 在loginModel.php中 当我尝试登录时,我收到此错误 EloquentUserProvider.php第110行中的错误异常:传递给Illumate\Auth\EloquentUserProvider的参数1::validateCreenti

  • 我正在创建一个laravel应用程序与自定义多重身份验证。我正在跟随这篇文章进行多重身份验证。https://pusher.com/tutorials/multiple-authentication-guards-laravel 我已经创建了登录和注册控制器定义的警卫和提供者,一切正常,我能够注册用户并登录他们。我写了一页(http://127.0.0.1:8000/admin)只有当管理员登录时