简体   繁体   English

如何通过 SpringBoot 从 Keycloak 获取访问令牌?

[英]How to get Access Token from Keycloak over SpringBoot?

I'm trying to get an Access Token from Keycloak over SpringBoot and did try the following example.我正在尝试通过 SpringBoot 从 Keycloak 获取访问令牌,并尝试了以下示例。 But the KeycloakAuthenticationToken token is null.但是KeycloakAuthenticationToken token是 null。

Does someone know another approach to get an Access 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;
}

Seems like I can get a token like this with ('org.keycloak:keycloak-admin-client'):似乎我可以使用('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();

If someone knows a more elegant way, I would appreciate if you let me know:)如果有人知道更优雅的方式,如果你让我知道,我将不胜感激:)

Thanks in advance!提前致谢!

Try the following:尝试以下操作:

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();

and the helper class:和助手 class:

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

Try this:尝试这个:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    KeycloakAuthenticationToken keycloakAuthenticationToken = (KeycloakAuthenticationToken) request.getUserPrincipal();
    KeycloakPrincipal<KeycloakSecurityContext> principal = (KeycloakPrincipal) keycloakAuthenticationToken.getPrincipal();
    String token = principal.getKeycloakSecurityContext().getIdTokenString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM