所以,我正在使用keycloak来保护我的服务。客户端应用程序从keycloak服务器获取访问令牌,并使用它来保护对Spring启动应用程序的访问。我使用bearer-only访问类型配置了我的Spring Boot应用程序的keycloak属性:
keycloak.realm = master
keycloak.realmKey = ...
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = boot-app
keycloak.bearer-only = true
keycloak.cors = true
Spring boot keycloak starter:
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
配置KeycloakWebSecurityConfigurerAdapter:
@Configuration
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
/**
* Registers the KeycloakAuthenticationProvider with the authentication manager.
*/
@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception
{
final KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakConfigResolver keycloakConfigResolver()
{
return new KeycloakSpringBootConfigResolver();
}
/**
* Defines the session authentication strategy.
*/
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy()
{
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(final HttpSecurity http) throws Exception
{
super.configure(http);
http
.authorizeRequests()
.antMatchers(
"/v2/api-docs",
"/configuration/ui",
"/swagger-resources",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/swagger-resources/configuration/ui",
"/swagger-ui.html",
"/swagger-resources/configuration/security").permitAll()
.antMatchers("/*").hasRole("user")
.anyRequest().authenticated();
}
}
现在,一切正常。我的问题是:Bearer令牌是JWT令牌,所有你需要解码它(并验证访问)是公钥,这是
keycloak.realmKey
为什么你需要其他设置,具体来说:
keycloak.auth-server-url
公共密钥不是您需要的一切吗?
提前致谢
答案 0 :(得分:4)
确实对于bearer-only
,您可能想知道为什么需要KC URL但是由于我们使用键旋转,因此realmKey
不再是必需的。这意味着您的应用将使用auth-server-url
属性从KC服务器动态检索公钥。
答案 1 :(得分:0)
如果您具有spring-boot应用程序,则最新的spring-security可以很好地处理它。您所需要做的就是在应用程序属性和所需的依赖项中定义jwks-uri。
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8780/auth/realms/my-realm/protocol/openid-connect/certs
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
请注意,如果需要,您也可以使用发行人uri代替jwks
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8780/auth/realms/my-realm