java - 如何通过 SpringBoot 从 Keycloak 获取访问令牌?
问题描述
我正在尝试通过 SpringBoot 从 Keycloak 获取访问令牌,并尝试了以下示例。但是KeycloakAuthenticationToken token
是空的。
有人知道另一种获取访问令牌的方法吗?
@GetMapping("/token")
public String getToken(HttpServletRequest request) throws IOException {
KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();
RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) token.getAccount().getKeycloakSecurityContext();
KeycloakSecurityContext context = token.getAccount().getKeycloakSecurityContext();
String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(session.getToken());
String idTokenPretty = JsonSerialization.writeValueAsPrettyString(session.getIdToken());
RefreshToken refreshToken;
try {
refreshToken = new JWSInput(session.getRefreshToken()).readJsonContent(RefreshToken.class);
} catch (JWSInputException e) {
throw new IOException(e);
}
String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken);
return refreshTokenPretty;
}
似乎我可以使用('org.keycloak:keycloak-admin-client')获得这样的令牌:
Keycloak keycloak = KeycloakBuilder.builder() //
.serverUrl(serverUrl) //
.realm(realm) //
.grantType(OAuth2Constants.PASSWORD) //
.clientId(clientId) //
.clientSecret(clientSecret) //
.username(userName) //
.password(password) //
.build();
AccessTokenResponse tok = keycloak.tokenManager().getAccessToken();
如果有人知道更优雅的方式,如果你让我知道,我将不胜感激:)
提前致谢!
解决方案
尝试以下操作:
HttpEntity<MultiValueMap<String, String>> request =
new TokenRequest.Builder(clientID, OAuth2Constants.PASSWORD)
.add("username", userName)
.add("password", password)
.build();
ResponseEntity<String> response = restTemplate.postForEntity( postUrl, request , String.class );
return response.getBody();
和助手类:
public class TokenRequest {
public static class Builder{
MultiValueMap<String, String> data;
public Builder(String clientID, String grant_type){
data = new LinkedMultiValueMap<>();
data.put("client_id", Collections.singletonList(clientID));
data.put("grant_type", Collections.singletonList(grant_type));
}
public Builder add(String key, String value){
data.put(key, Collections.singletonList(value));
return this;
}
public HttpEntity<MultiValueMap<String, String>> build(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
return new HttpEntity<>(data, headers);
}
}
private TokenRequest(){
}
}
推荐阅读
- javascript - 将样式转换为字符串
- java - 从经纬度Java获取国家isocode
- apache-kafka - 是否可以将一个spring kafka消费者分配给一个实例,将另一个消费者分配给同一服务的另一个实例
- angular - 我如何使我的目标输入将内容推向离子
- javascript - 角度 onpush 组件仅在模板内使用异步管道重新渲染
- reactjs - 如何从 ReactJS 重定向到内部和外部页面
- pandas - 在 groupby 之后相乘
- javascript - LitePicker / 日期选择器 js - 在日期的当前锚点内添加一个额外的 div
- go - 如何对行进行部分更新方法
- ecmascript-6 - 在函数属性中正确合并两个数组