Search in sources :

Example 31 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class OAuthRequestAuthenticator method resolveCode.

/**
 * Start or continue the oauth login process.
 * <p/>
 * if code query parameter is not present, then browser is redirected to authUrl.  The redirect URL will be
 * the URL of the current request.
 * <p/>
 * If code query parameter is present, then an access token is obtained by invoking a secure request to the codeUrl.
 * If the access token is obtained, the browser is again redirected to the current request URL, but any OAuth
 * protocol specific query parameters are removed.
 *
 * @return null if an access token was obtained, otherwise a challenge is returned
 */
protected AuthChallenge resolveCode(String code) {
    // abort if not HTTPS
    if (!isRequestSecure() && deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
        log.error("Adapter requires SSL. Request: " + facade.getRequest().getURI());
        return challenge(403, OIDCAuthenticationError.Reason.SSL_REQUIRED, null);
    }
    log.debug("checking state cookie for after code");
    AuthChallenge challenge = checkStateCookie();
    if (challenge != null)
        return challenge;
    AccessTokenResponse tokenResponse = null;
    strippedOauthParametersRequestUri = rewrittenRedirectUri(stripOauthParametersFromRedirect());
    try {
        // For COOKIE store we don't have httpSessionId and single sign-out won't be available
        String httpSessionId = deployment.getTokenStore() == TokenStore.SESSION ? reqAuthenticator.changeHttpSessionId(true) : null;
        tokenResponse = ServerRequest.invokeAccessCodeToToken(deployment, code, strippedOauthParametersRequestUri, httpSessionId);
    } catch (ServerRequest.HttpFailure failure) {
        log.error("failed to turn code into token");
        log.error("status from server: " + failure.getStatus());
        if (failure.getError() != null && !failure.getError().trim().isEmpty()) {
            log.error("   " + failure.getError());
        }
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    } catch (IOException e) {
        log.error("failed to turn code into token", e);
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    }
    tokenString = tokenResponse.getToken();
    refreshToken = tokenResponse.getRefreshToken();
    idTokenString = tokenResponse.getIdToken();
    log.debug("Verifying tokens");
    if (log.isTraceEnabled()) {
        logToken("\taccess_token", tokenString);
        logToken("\tid_token", idTokenString);
        logToken("\trefresh_token", refreshToken);
    }
    try {
        AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, idTokenString, deployment);
        token = tokens.getAccessToken();
        idToken = tokens.getIdToken();
        log.debug("Token Verification succeeded!");
    } catch (VerificationException e) {
        log.error("failed verification of token: " + e.getMessage());
        return challenge(403, OIDCAuthenticationError.Reason.INVALID_TOKEN, null);
    }
    if (tokenResponse.getNotBeforePolicy() > deployment.getNotBefore()) {
        deployment.updateNotBefore(tokenResponse.getNotBeforePolicy());
    }
    if (token.getIssuedAt() < deployment.getNotBefore()) {
        log.error("Stale token");
        return challenge(403, OIDCAuthenticationError.Reason.STALE_TOKEN, null);
    }
    log.debug("successful authenticated");
    return null;
}
Also used : AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) VerificationException(org.keycloak.common.VerificationException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 32 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class BasicAuthRequestAuthenticator method getToken.

protected AccessTokenResponse getToken(String username, String password) throws Exception {
    AccessTokenResponse tokenResponse = null;
    HttpClient client = deployment.getClient();
    HttpPost post = new HttpPost(deployment.getTokenUrl());
    java.util.List<NameValuePair> formparams = new java.util.ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
    formparams.add(new BasicNameValuePair("username", username));
    formparams.add(new BasicNameValuePair("password", password));
    ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
    post.setEntity(form);
    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    if (status != 200) {
        EntityUtils.consumeQuietly(entity);
        throw new java.io.IOException("Bad status: " + status);
    }
    if (entity == null) {
        throw new java.io.IOException("No Entity");
    }
    java.io.InputStream is = entity.getContent();
    try {
        tokenResponse = JsonSerialization.readValue(is, AccessTokenResponse.class);
    } finally {
        try {
            is.close();
        } catch (java.io.IOException ignored) {
        }
    }
    return (tokenResponse);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 33 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class RefreshableKeycloakSecurityContext method refreshExpiredToken.

/**
 * @param checkActive if true, then we won't send refresh request if current accessToken is still active.
 * @return true if accessToken is active or was successfully refreshed
 */
public boolean refreshExpiredToken(boolean checkActive) {
    if (checkActive) {
        if (log.isTraceEnabled()) {
            log.trace("checking whether to refresh.");
        }
        if (isActive() && isTokenTimeToLiveSufficient(this.token))
            return true;
    }
    // Might be serialized in HttpSession?
    if (this.deployment == null || refreshToken == null)
        return false;
    if (!this.getRealm().equals(this.deployment.getRealm())) {
        // this should not happen, but let's check it anyway
        return false;
    }
    if (log.isTraceEnabled()) {
        log.trace("Doing refresh");
    }
    // 
    synchronized (this) {
        if (checkActive) {
            log.trace("Checking whether token has been refreshed in another thread already.");
            if (isActive() && isTokenTimeToLiveSufficient(this.token))
                return true;
        }
        AccessTokenResponse response;
        try {
            response = ServerRequest.invokeRefresh(deployment, refreshToken);
        } catch (IOException e) {
            log.error("Refresh token failure", e);
            return false;
        } catch (ServerRequest.HttpFailure httpFailure) {
            final Logger.Level logLevel = httpFailure.getError().contains("Refresh token expired") ? Logger.Level.WARN : Logger.Level.ERROR;
            log.log(logLevel, "Refresh token failure status: " + httpFailure.getStatus() + " " + httpFailure.getError());
            return false;
        }
        if (log.isTraceEnabled()) {
            log.trace("received refresh response");
        }
        String tokenString = response.getToken();
        AccessToken token = null;
        IDToken idToken = null;
        try {
            AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, response.getIdToken(), deployment);
            token = tokens.getAccessToken();
            idToken = tokens.getIdToken();
            log.debug("Token Verification succeeded!");
        } catch (VerificationException e) {
            log.error("failed verification of token");
            return false;
        }
        // If the TTL is greater-or-equal to the expire time on the refreshed token, have to abort or go into an infinite refresh loop
        if (!isTokenTimeToLiveSufficient(token)) {
            log.error("failed to refresh the token with a longer time-to-live than the minimum");
            return false;
        }
        if (response.getNotBeforePolicy() > deployment.getNotBefore()) {
            deployment.updateNotBefore(response.getNotBeforePolicy());
        }
        if (idToken != null) {
            this.idToken = idToken;
            this.idTokenString = response.getIdToken();
        }
        this.token = token;
        if (response.getRefreshToken() != null) {
            if (log.isTraceEnabled()) {
                log.trace("Setup new refresh token to the security context");
            }
            this.refreshToken = response.getRefreshToken();
        }
        this.tokenString = tokenString;
        if (tokenStore != null) {
            tokenStore.refreshCallback(this);
        }
    }
    return true;
}
Also used : AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 34 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class KeycloakInstalled method refreshToken.

public void refreshToken() throws IOException, ServerRequest.HttpFailure, VerificationException {
    AccessTokenResponse tokenResponse = ServerRequest.invokeRefresh(deployment, refreshToken);
    parseAccessToken(tokenResponse);
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 35 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class KeycloakInstalled method refreshToken.

public void refreshToken(String refreshToken) throws IOException, ServerRequest.HttpFailure, VerificationException {
    AccessTokenResponse tokenResponse = ServerRequest.invokeRefresh(deployment, refreshToken);
    parseAccessToken(tokenResponse);
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Aggregations

AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)74 Response (javax.ws.rs.core.Response)30 Test (org.junit.Test)30 OAuthClient (org.keycloak.testsuite.util.OAuthClient)25 Client (javax.ws.rs.client.Client)24 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)17 Form (javax.ws.rs.core.Form)15 WebTarget (javax.ws.rs.client.WebTarget)14 AccessToken (org.keycloak.representations.AccessToken)14 IOException (java.io.IOException)12 ClientResource (org.keycloak.admin.client.resource.ClientResource)7 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)7 AuthzClient (org.keycloak.authorization.client.AuthzClient)5 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)5 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)5 UncaughtServerErrorExpected (org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)5 InputStream (java.io.InputStream)4 URI (java.net.URI)4 NameValuePair (org.apache.http.NameValuePair)4 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)4