我目前正在try 实现一个简单的Spring Boot后端应用程序的安全性.为此,我打算将Keyloak与Spring Security结合使用.在try 了几十个教程设置(只是一个基本的过滤器/安全配置)后,我对为什么SecurityFilterChain
个不起作用一无所知.
作为参考-以下是我的依赖项:
- Org.springframework.boot:spring-boot-starter:3.1.0
- Org.springframework.boot:spring-boot-starter-web:3.1.0
- Org.springframework.boot:spring-boot-starter-oauth2-client:3.1.0
- Org.springframework.boot:spring-boot-starter-security:3.1.0
- Org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.1.0
- Org.projectlombok:龙目岛:1.18.26
- Org.springframework.boot:spring-boot-starter-test:3.1.0
全部安装了Spring Boot 3.1.0!由于网上的material 是最近两年的,我也try 了不同的版本(例如<spring-security.version>6.1.1</spring-security.version>
个,等等).
至于我的application.properties
美元,我增加了最基本的设置:
spring.security.oauth2.client.registration.keycloak.client-id=[client-id]
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.scope=openid
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/dev
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username
就是这样!现在谈一谈我经历过的unsuccessfully种不同的方法:
在那里,它指定了要与返回SecurityFilterChain
的@Bean
一起使用的SecurityConfig:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/customers*")
.hasRole("USER")
.anyRequest()
.permitAll();
http.oauth2Login()
.and()
.logout()
.addLogoutHandler(keycloakLogoutHandler)
.logoutSuccessUrl("/");
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
...显然,'authorizeRequests()'
是不受欢迎的.同样适用于'oauth2Login()'
(即使标记为删除)!
2. GitHub Issue #10187 discussion个
在前面提到的问题中,爆发了一场深入的讨论,许多成员分享了他们的代码片段.这是一个非常新的话题(2022年),因此我认为它仍然适用于当前的标准.
@Configuration
@RequiredArgsConstructor
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final KeycloakLogoutHandler keycloakLogoutHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //
.anyRequest().fullyAuthenticated() //
.and().oauth2Client() //
.and().oauth2Login().tokenEndpoint().and().userInfoEndpoint().userAuthoritiesMapper(userAuthoritiesMapper()) //
.and().and()
.logout().addLogoutHandler(keycloakLogoutHandler)
;
}
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
[...]
我按照这些思路玩弄了一些东西.再说一遍.除了已知的标记为deprecated
(oauth2Client()
、oauth2Login()
等)的罪魁祸首之外,最大的问题是WebSecurityConfigurerAdapter
是ALSO已弃用.当我打开issue #12514门时,我被告知我应该继续走SecurityFilterChain
路,这与第一种方法类似.
不管怎样,我现在已经烧掉了大约10多个教程,但没有找到一个可以工作的项目--考虑到KeyCloak的大小--非常奇怪.我发现的唯一好消息是go 年的老KeyCloak adapters were deprecated人...虽然我还没有用过,就像你在上面看到的那样.
我想设置一个SIMPLE SecurityConfig
作为建造的基础.只需从请求中获取承载令牌(BTW KeyCloak相关设置工作),然后验证JWT并将用户角色/许可与端点(preferably not a global setting, but a local one per endpoint basis)上所需的角色进行比较.