Search in sources :

Example 21 with AccessTokenResponse

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

the class AbstractOAuth2IdentityProvider method hasExternalExchangeToken.

/**
 * check to see if we have a token exchange in session
 * in other words check to see if this session was created by an external exchange
 * @param tokenUserSession
 * @param params
 * @return
 */
protected Response hasExternalExchangeToken(EventBuilder event, UserSessionModel tokenUserSession, MultivaluedMap<String, String> params) {
    if (getConfig().getAlias().equals(tokenUserSession.getNote(OIDCIdentityProvider.EXCHANGE_PROVIDER))) {
        String requestedType = params.getFirst(OAuth2Constants.REQUESTED_TOKEN_TYPE);
        if ((requestedType == null || requestedType.equals(OAuth2Constants.ACCESS_TOKEN_TYPE))) {
            String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
            if (accessToken != null) {
                AccessTokenResponse tokenResponse = new AccessTokenResponse();
                tokenResponse.setToken(accessToken);
                tokenResponse.setIdToken(null);
                tokenResponse.setRefreshToken(null);
                tokenResponse.setRefreshExpiresIn(0);
                tokenResponse.setExpiresIn(0);
                tokenResponse.getOtherClaims().clear();
                tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
                event.success();
                return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
            }
        } else if (OAuth2Constants.ID_TOKEN_TYPE.equals(requestedType)) {
            String idToken = tokenUserSession.getNote(OIDCIdentityProvider.FEDERATED_ID_TOKEN);
            if (idToken != null) {
                AccessTokenResponse tokenResponse = new AccessTokenResponse();
                tokenResponse.setToken(null);
                tokenResponse.setIdToken(idToken);
                tokenResponse.setRefreshToken(null);
                tokenResponse.setRefreshExpiresIn(0);
                tokenResponse.setExpiresIn(0);
                tokenResponse.getOtherClaims().clear();
                tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ID_TOKEN_TYPE);
                event.success();
                return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
            }
        }
    }
    return null;
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 22 with AccessTokenResponse

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

the class OIDCIdentityProvider method exchangeSessionToken.

@Override
protected Response exchangeSessionToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    String refreshToken = tokenUserSession.getNote(FEDERATED_REFRESH_TOKEN);
    String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
    String idToken = tokenUserSession.getNote(FEDERATED_ID_TOKEN);
    if (accessToken == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    try (VaultStringSecret vaultStringSecret = session.vault().getStringSecret(getConfig().getClientSecret())) {
        long expiration = Long.parseLong(tokenUserSession.getNote(FEDERATED_TOKEN_EXPIRATION));
        if (expiration == 0 || expiration > Time.currentTime()) {
            AccessTokenResponse tokenResponse = new AccessTokenResponse();
            tokenResponse.setExpiresIn(expiration);
            tokenResponse.setToken(accessToken);
            tokenResponse.setIdToken(null);
            tokenResponse.setRefreshToken(null);
            tokenResponse.setRefreshExpiresIn(0);
            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();
        }
        String response = getRefreshTokenRequest(session, refreshToken, getConfig().getClientId(), vaultStringSecret.get().orElse(getConfig().getClientSecret())).asString();
        if (response.contains("error")) {
            logger.debugv("Error refreshing token, refresh token expiration?: {0}", response);
            event.detail(Details.REASON, "requested_issuer token expired");
            event.error(Errors.INVALID_TOKEN);
            return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
        }
        AccessTokenResponse newResponse = JsonSerialization.readValue(response, AccessTokenResponse.class);
        long accessTokenExpiration = newResponse.getExpiresIn() > 0 ? Time.currentTime() + newResponse.getExpiresIn() : 0;
        tokenUserSession.setNote(FEDERATED_TOKEN_EXPIRATION, Long.toString(accessTokenExpiration));
        tokenUserSession.setNote(FEDERATED_REFRESH_TOKEN, newResponse.getRefreshToken());
        tokenUserSession.setNote(FEDERATED_ACCESS_TOKEN, newResponse.getToken());
        tokenUserSession.setNote(FEDERATED_ID_TOKEN, newResponse.getIdToken());
        newResponse.setIdToken(null);
        newResponse.setRefreshToken(null);
        newResponse.setRefreshExpiresIn(0);
        newResponse.getOtherClaims().clear();
        newResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
        newResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
        event.success();
        return Response.ok(newResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : VaultStringSecret(org.keycloak.vault.VaultStringSecret) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 23 with AccessTokenResponse

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

the class OIDCIdentityProvider method authenticationFinished.

@Override
public void authenticationFinished(AuthenticationSessionModel authSession, BrokeredIdentityContext context) {
    AccessTokenResponse tokenResponse = (AccessTokenResponse) context.getContextData().get(FEDERATED_ACCESS_TOKEN_RESPONSE);
    int currentTime = Time.currentTime();
    long expiration = tokenResponse.getExpiresIn() > 0 ? tokenResponse.getExpiresIn() + currentTime : 0;
    authSession.setUserSessionNote(FEDERATED_TOKEN_EXPIRATION, Long.toString(expiration));
    authSession.setUserSessionNote(FEDERATED_REFRESH_TOKEN, tokenResponse.getRefreshToken());
    authSession.setUserSessionNote(FEDERATED_ACCESS_TOKEN, tokenResponse.getToken());
    authSession.setUserSessionNote(FEDERATED_ID_TOKEN, tokenResponse.getIdToken());
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 24 with AccessTokenResponse

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

the class EntitlementAPITest method testUsingExpiredToken.

@Test
public void testUsingExpiredToken() throws Exception {
    ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
    AuthorizationResource authorization = client.authorization();
    JSPolicyRepresentation policy = new JSPolicyRepresentation();
    policy.setName(KeycloakModelUtils.generateId());
    policy.setCode("$evaluation.grant();");
    authorization.policies().js().create(policy).close();
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName("Sensors");
    try (Response response = authorization.resources().create(resource)) {
        resource = response.readEntity(ResourceRepresentation.class);
    }
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName("View Sensor");
    permission.addPolicy(policy.getName());
    authorization.permissions().resource().create(permission).close();
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AccessTokenResponse response = authzClient.authorization(accessToken).authorize();
    assertNotNull(response.getToken());
    getRealm().logoutAll();
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission("Sensors");
    request.setSubjectToken(accessToken);
    try {
        authzClient.authorization().authorize(request);
        fail("should fail, session invalidated");
    } catch (Exception e) {
        Throwable expected = e.getCause();
        assertEquals(400, HttpResponseException.class.cast(expected).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected).toString().contains("unauthorized_client"));
    }
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) ExpectedException(org.junit.rules.ExpectedException) IOException(java.io.IOException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) AuthzClient(org.keycloak.authorization.client.AuthzClient) ClientResource(org.keycloak.admin.client.resource.ClientResource) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test)

Example 25 with AccessTokenResponse

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

the class UmaGrantTypeTest method testRefreshRpt.

@Test
public void testRefreshRpt() {
    AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password");
    AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB"));
    String rpt = response.getToken();
    assertNotNull(rpt);
    AccessToken accessToken = toAccessToken(rpt);
    AccessToken.Authorization authorization = accessToken.getAuthorization();
    assertNotNull(authorization);
    Collection<Permission> permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
    String refreshToken = response.getRefreshToken();
    assertNotNull(refreshToken);
    AccessToken refreshTokenToken = toAccessToken(refreshToken);
    assertNotNull(refreshTokenToken.getAuthorization());
    Client client = AdminClientUtil.createResteasyClient();
    UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
    URI uri = OIDCLoginProtocolService.tokenUrl(builder).build(REALM_NAME);
    WebTarget target = client.target(uri);
    Form parameters = new Form();
    parameters.param("grant_type", OAuth2Constants.REFRESH_TOKEN);
    parameters.param(OAuth2Constants.REFRESH_TOKEN, refreshToken);
    AccessTokenResponse refreshTokenResponse = target.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")).post(Entity.form(parameters)).readEntity(AccessTokenResponse.class);
    assertNotNull(refreshTokenResponse.getToken());
    refreshToken = refreshTokenResponse.getRefreshToken();
    refreshTokenToken = toAccessToken(refreshToken);
    assertNotNull(refreshTokenToken.getAuthorization());
    AccessToken refreshedToken = toAccessToken(rpt);
    authorization = refreshedToken.getAuthorization();
    assertNotNull(authorization);
    permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
    refreshTokenResponse = target.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")).post(Entity.form(parameters)).readEntity(AccessTokenResponse.class);
    assertNotNull(refreshTokenResponse.getToken());
    refreshToken = refreshTokenResponse.getRefreshToken();
    refreshTokenToken = toAccessToken(refreshToken);
    assertNotNull(refreshTokenToken.getAuthorization());
    refreshedToken = toAccessToken(rpt);
    authorization = refreshedToken.getAuthorization();
    assertNotNull(authorization);
    permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) Form(javax.ws.rs.core.Form) URI(java.net.URI) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) WebTarget(javax.ws.rs.client.WebTarget) AuthzClient(org.keycloak.authorization.client.AuthzClient) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) UriBuilder(javax.ws.rs.core.UriBuilder) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test)

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