Search in sources :

Example 36 with AccessTokenResponse

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

the class JaxrsOAuthClient method resolveBearerToken.

public String resolveBearerToken(String redirectUri, String code) {
    redirectUri = stripOauthParametersFromRedirect(redirectUri);
    Form codeForm = new Form().param(OAuth2Constants.GRANT_TYPE, "authorization_code").param(OAuth2Constants.CODE, code).param(OAuth2Constants.CLIENT_ID, clientId).param(OAuth2Constants.REDIRECT_URI, redirectUri);
    for (Map.Entry<String, Object> entry : credentials.entrySet()) {
        codeForm.param(entry.getKey(), (String) entry.getValue());
    }
    Response res = client.target(tokenUrl).request().post(Entity.form(codeForm));
    try {
        if (res.getStatus() == 400) {
            throw new BadRequestException();
        } else if (res.getStatus() != 200) {
            throw new InternalServerErrorException(new Exception("Unknown error when getting acess token"));
        }
        AccessTokenResponse tokenResponse = res.readEntity(AccessTokenResponse.class);
        return tokenResponse.getToken();
    } finally {
        res.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Map(java.util.Map) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException)

Example 37 with AccessTokenResponse

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

the class BasicAuthenticationOAuthTranslator method authenticate.

@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    if (!enabled) {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    logger.debug("BASIC authenticate injector checking for " + AUTHORIZATION_HEADER + " header.");
    final HeaderMap headers = exchange.getRequestHeaders();
    final Collection<String> vals = headers.remove(AUTHORIZATION_HEADER);
    String basicAuth = null;
    String bearerAuth = null;
    final List<String> resultValues = new ArrayList<>();
    if (vals != null) {
        for (final String value : vals) {
            logger.debug("Found Authorization header: '{}'", value);
            if (value.toLowerCase().startsWith(BASIC_AUTH_PREFIX)) {
                logger.debug("detected basic auth");
                basicAuth = value;
            } else if (value.toLowerCase().startsWith(BEARER_AUTH_PREFIX)) {
                bearerAuth = value;
                resultValues.add(value);
            } else {
                resultValues.add(value);
            }
        }
    }
    if (bearerAuth == null && basicAuth != null) {
        final UserPass userPass = UserPass.parse(basicAuth);
        logger.debug("Parsed BASIC authorization: {}", userPass);
        if (userPass != null) {
            final AccessTokenResponse token = lookupToken(userPass);
            if (token != null) {
                final String encodedToken = token.getToken();
                logger.debug("Raw token: {}", encodedToken);
                final String value = BEARER_AUTH_PREFIX + " " + encodedToken;
                logger.debug("Adding {} value: {}", AUTHORIZATION_HEADER, value);
                logger.info("BASIC authentication translated into OAuth 2.0 bearer token. Handing off to Keycloak.");
                resultValues.add(value);
                // KeycloakBearerTokenDebug.debugToken( encodedToken );
                exchange.getResponseHeaders().add(new HttpString(INDY_BEARER_TOKEN), encodedToken);
            }
        }
    }
    logger.debug("Re-adding {} values: {}", AUTHORIZATION_HEADER, resultValues);
    headers.addAll(new HttpString(AUTHORIZATION_HEADER), resultValues);
    // The best we can do is lookup the token for the given basic auth fields, and inject it for keycloak to use.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : HeaderMap(io.undertow.util.HeaderMap) ArrayList(java.util.ArrayList) UserPass(org.commonjava.indy.subsys.http.util.UserPass) HttpString(io.undertow.util.HttpString) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) HttpString(io.undertow.util.HttpString)

Example 38 with AccessTokenResponse

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

the class TestAbstractOidcRestModule method prepareClient.

private WebClient prepareClient() {
    AccessTokenResponse result = getAuthzClient().obtainAccessToken(USER_ADMINISTRATOR_USERNAME, USER_ADMINISTRATOR_PASSWORD);
    WebClient client = prepareClient(result.getTokenType(), result.getToken());
    client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value());
    return client;
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 39 with AccessTokenResponse

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

the class AuthUtil method ensureToken.

public static String ensureToken(ConfigData config) {
    checkAuthInfo(config);
    RealmConfigData realmConfig = config.sessionRealmConfigData();
    long now = currentTimeMillis();
    // if it's less than 5s to expiry, renew it
    if (realmConfig.getExpiresAt() - now < 5000) {
        // if it's less than 5s to expiry, fail with credentials expired
        if (realmConfig.getRefreshExpiresAt() != null && realmConfig.getRefreshExpiresAt() - now < 5000) {
            throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
        }
        if (realmConfig.getSigExpiresAt() != null && realmConfig.getSigExpiresAt() - now < 5000) {
            throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
        }
        try {
            String authorization = null;
            StringBuilder body = new StringBuilder();
            if (realmConfig.getRefreshToken() != null) {
                body.append("grant_type=refresh_token").append("&refresh_token=").append(realmConfig.getRefreshToken());
            } else {
                body.append("grant_type=").append(realmConfig.getGrantTypeForAuthentication());
            }
            body.append("&client_id=").append(urlencode(realmConfig.getClientId()));
            if (realmConfig.getSigningToken() != null) {
                body.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer").append("&client_assertion=").append(realmConfig.getSigningToken());
            } else if (realmConfig.getSecret() != null) {
                authorization = BasicAuthHelper.createHeader(realmConfig.getClientId(), realmConfig.getSecret());
            }
            InputStream result = doPost(realmConfig.serverUrl() + "/realms/" + realmConfig.realm() + "/protocol/openid-connect/token", APPLICATION_FORM_URL_ENCODED, APPLICATION_JSON, body.toString(), authorization);
            AccessTokenResponse token = JsonSerialization.readValue(result, AccessTokenResponse.class);
            saveMergeConfig(cfg -> {
                RealmConfigData realmData = cfg.sessionRealmConfigData();
                realmData.setToken(token.getToken());
                realmData.setRefreshToken(token.getRefreshToken());
                realmData.setExpiresAt(currentTimeMillis() + token.getExpiresIn() * 1000);
                if (token.getRefreshToken() != null) {
                    realmData.setRefreshExpiresAt(currentTimeMillis() + token.getRefreshExpiresIn() * 1000);
                }
            });
            return token.getToken();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unexpected error", e);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read Refresh Token response", e);
        }
    }
    return realmConfig.getToken();
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 40 with AccessTokenResponse

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

the class AbstractOAuth2IdentityProvider method exchangeSessionToken.

protected Response exchangeSessionToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
    if (accessToken == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    AccessTokenResponse tokenResponse = new AccessTokenResponse();
    tokenResponse.setToken(accessToken);
    tokenResponse.setIdToken(null);
    tokenResponse.setRefreshToken(null);
    tokenResponse.setRefreshExpiresIn(0);
    tokenResponse.getOtherClaims().clear();
    tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    event.success();
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
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