从Spring Boot Security迁移到Keycloak

6

我希望将我的旧的Spring Boot安全应用程序迁移到Keycloak。以下是我的安全配置。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private CustomUserDetailsService customUserDetailsService;
     @Override
        protected void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();

         http
         .authorizeRequests()
             .antMatchers("/*", "/static/**", "/css/**", "/js/**", "/images/**").permitAll()
             .antMatchers("/school-admin/*").hasAuthority("SCHOOL_ADMIN").anyRequest().fullyAuthenticated()
             .antMatchers("/teacher/*").hasAuthority("TEACHER").anyRequest().fullyAuthenticated()
             .anyRequest().authenticated().and()

         .formLogin()
             .loginPage("/login.html").defaultSuccessUrl("/loginSuccess.html")
            .failureUrl("/login.html?error").permitAll().and()

         .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout.html")).logoutSuccessUrl("/login.html?logout");

     }

     @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
        }
}

我已经安装了Keycloak,并且它在8080端口上运行。我发现一个问题,就是我们应该在Keycloak管理页面上创建角色和用户,但是我的当前系统是,用户和角色存储在我的MySQL数据库中。我不想在Keycloak中插入这些用户和角色以进行身份验证和授权。

1个回答

2

首先,显然需要一个正在运行的Keycloak实例,我认为可以通过在线文档完成此操作。我们在Wildfly实例上使用Keycloak。 接下来,您需要在Keycloak中定义一个领域和至少一个客户端,该客户端将用于与您的Spring Boot应用程序连接。在您的应用程序的POM中,您需要添加关于Keycloak适配器的依赖项,例如:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-tomcat8-adapter</artifactId>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-adapter</artifactId>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
</dependency>

其余的配置可以在您的application.properties文件中完成。这是您配置适配器连接到Keycloak并保护哪些部分应用程序的地方。下面是一个示例:

keycloak.realm=myrealm #realm that you have created in keycloak, contains your client
keycloak.auth-server-url=KeycloakHOST:KeycloakPort/auth # Substitute with your settings
keycloak.ssl-required=none
keycloak.resource=myclient
#keycloak.use-resource-role-mappings=true
keycloak.enable-basic-auth=true # we use basic authentication in this example
keycloak.credentials.secret=2dcf74ca-4e4f-44bf-9774-6c32c12783d3 # Secret generated for you client in keycloak
keycloak.cors=true
keycloak.cors-allowed-headers=x-requested-with,origin,content-type,accept,authorization
keycloak.cors-allowed-methods=GET,POST,DELETE,PUT,OPTIONS
keycloak.cors-max-age=3600
keycloak.expose-token=true
keycloak.bearer-only=true
keycloak.securityConstraints[0].securityCollections[0].name=adminRule
keycloak.securityConstraints[0].securityCollections[0].authRoles[0]=SCHOOL_ADMIN
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/school-admin/*
keycloak.securityConstraints[1].securityCollections[0].name=teacherRule
keycloak.securityConstraints[1].securityCollections[0].authRoles[0]=TEACHER
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/teacher/*

这就是在你的Spring Boot应用程序中需要做的基本操作。所有其他未被上述规则覆盖的端点仍然对所有人可用。你可以在这里找到一个非常好的教程,它是我所描述的更长版本。


你可以编写自定义提供程序,我之前没有亲自做过,但应该是可能的。请参阅 https://keycloak.gitbooks.io/server-adminstration-guide/content/topics/user-federation/custom.html 了解一些信息,也可以适当地进行谷歌搜索。通常,您需要实现一个界面,这个实现将转到您的数据库并查询给定的用户数据。唯一的问题是您是否可以提供接口所需的所有数据,但您需要检查一下。 - hecko84
我刚刚找到了一个更好的例子,它使用了一些与JPA连接的数据库,请看 https://github.com/keycloak/keycloak/tree/master/examples/providers/user-storage-jpa 事实上,这也是在keycloak中拥有FDI功能的重要优势之一,因为您可以插入多个提供程序并共同使用它们。 - hecko84
我会查看一下,你找到了任何Spring Boot的示例吗? - boycod3
嗯,我已经有一段时间没有处理这个问题了,但是除了我上面描述的用法之外,我还没有看到其他不同的用法。我们有一些类似的需求,但是通过采用不同的端点策略来解决,例如 /public/user/registration 用于自由可用资源。 - hecko84
1
@hecko84的帖子更新链接 - https://github.com/keycloak/keycloak-quickstarts/tree/latest/user-storage-jpa - denov
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接