nej*_*asa 2 jwt spring-boot bearer-token keycloak keycloak-services
所以,我使用 keycloak 来保护我的服务。客户端应用程序从 keycloak 服务器获取访问令牌,并使用它来保护对 Spring boot 应用程序的访问。我已经使用仅持有者访问类型使用 keycloak 属性配置了我的 Spring Boot 应用程序:
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
Run Code Online (Sandbox Code Playgroud)
Spring Boot keycloak 启动器:
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并配置 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",
"/swagge??r-ui.html",
"/swagger-resources/configuration/security").permitAll()
.antMatchers("/*").hasRole("user")
.anyRequest().authenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,一切正常。我的问题是:不记名令牌是 JWT 令牌,您需要对其进行解码(并验证访问)的是公钥,即
keycloak.realmKey
Run Code Online (Sandbox Code Playgroud)
为什么需要其他设置,特别是:
keycloak.auth-server-url
Run Code Online (Sandbox Code Playgroud)
公钥不是你需要的一切吗?
提前致谢
事实上,bearer-only您可能想知道为什么需要 KC URL,但由于一些 KC 版本realmKey不再是强制性的,因为我们使用密钥轮换。这意味着您的应用程序将使用该auth-server-url属性从 KC 服务器动态检索公钥。
| 归档时间: |
|
| 查看次数: |
8558 次 |
| 最近记录: |