首页 > 解决方案 > 如何通过 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();

如果有人知道更优雅的方式,如果你让我知道,我将不胜感激:)

提前致谢!

标签: javaspring-bootkeycloakaccess-token

解决方案


尝试以下操作:

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(){
    }
}

推荐阅读