我有带有keycloak依赖项的Spring应用程序。 前端发送到我的后端承载令牌,我想使用此令牌从密钥斗篷中获取用户名和他的UUID。
这是我的密钥斗篷配置。
@Configuration
@ComponentScan(
basePackageClasses = KeycloakSecurityComponents.class,
excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
@EnableWebSecurity
class KeycloakConfig extends KeycloakWebSecurityConfigurerAdapter {
@Bean
public KeycloakConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.csrf().disable()
.sessionManagement()
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMINS")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().permitAll();
}
}
在此端点中,我正在获取授权标头:
@PostMapping(value = "/save/{title}")
@ResponseBody
public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file, @PathVariable("title") String title, @RequestHeader("Authorization") String authHeader) {
//get user by token?
}
答案 0 :(得分:0)
很快,我会解析公共密钥和访问令牌以获取AccessToken类,该类具有您所需的全部内容(accessToken.getId()和accessToken.getPreferredUsername())
@Autowired
private KeycloakSpringBootProperties keycloakProperties;
public String getRealm() {
return keycloakProperties.getRealm();
}
public String getAuthServerUrl() {
return keycloakProperties.getAuthServerUrl();
}
public String getRealmUrl() {
return getAuthServerUrl()
+ "/realms/"
+ getRealm();
}
public String getOpenIdConnectUrl() {
return getRealmUrl() + "/protocol/openid-connect";
}
public String getOpenIdConnectCertsUrl() {
return getOpenIdConnectUrl() + "/certs";
}
public AccessToken loadAccessToken(String accessToken) throws TokenNotActiveException, VerificationException, NoSuchFieldException {
PublicKey publicKey = new KeyCloakRsaKeyLoader().getPublicKeyFromKeyCloak(getOpenIdConnectCertsUrl());
String realmUrl = keyCloakConnectionProvider.getRealmUrl();
AccessToken token =
RSATokenVerifier.verifyToken(
accessToken,
publicKey,
realmUrl,
true,
true);
return token;
}