Search in sources :

Example 41 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class ClientResource method deleteInstance.

public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request) {
    String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    Map<String, String> responseVal = new HashMap<String, String>();
    JsonValue response;
    try {
        String realm = request.getAdditionalParameter("realm");
        if (realm == null) {
            realm = "/";
        }
        manager.deleteIdentity(resourceId, realm);
        try {
            //delete the tokens associated with that client_id
            final TokenFilter tokenFilter = new TokenFilterBuilder().and().withAttribute(OAuthTokenField.CLIENT_ID.getField(), resourceId).withAttribute(OAuthTokenField.REALM.getField(), realm).build();
            store.deleteOnQueryAsync(tokenFilter);
        } catch (CoreTokenException e) {
            if (auditLogger.isAuditLogEnabled()) {
                String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
                auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
            }
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId);
            }
            throw new InternalServerErrorException("Unable to delete client", e);
        }
        responseVal.put("success", "true");
        response = new JsonValue(responseVal);
        ResourceResponse resource = newResourceResponse("results", "1", response);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "DELETED_CLIENT", response.toString() };
            auditLogger.logAccessMessage("DELETED_CLIENT", obs, null);
            if (debug.messageEnabled()) {
                debug.error("ClientResource :: DELETE by " + principal + ": delete client with ID, " + resourceId);
            }
        }
        return newResultPromise(resource);
    } catch (IdRepoException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    } catch (SSOException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    } catch (InternalServerErrorException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    }
}
Also used : Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) SSOException(com.iplanet.sso.SSOException) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter)

Example 42 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class OpenAMTokenStore method createRefreshToken.

@Override
public RefreshToken createRefreshToken(String grantType, String clientId, String resourceOwnerId, String redirectUri, Set<String> scope, OAuth2Request request, String validatedClaims) throws ServerException, NotFoundException {
    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    logger.message("Create refresh token");
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    final long lifeTime;
    if (clientRegistration == null) {
        lifeTime = providerSettings.getRefreshTokenLifetime();
    } else {
        lifeTime = clientRegistration.getRefreshTokenLifeTime(providerSettings);
    }
    long expiryTime = lifeTime < 0 ? -1 : lifeTime + System.currentTimeMillis();
    AuthorizationCode token = request.getToken(AuthorizationCode.class);
    String authModules = null;
    String acr = null;
    if (token != null) {
        authModules = token.getAuthModules();
        acr = token.getAuthenticationContextClassReference();
    }
    RefreshToken currentRefreshToken = request.getToken(RefreshToken.class);
    if (currentRefreshToken != null) {
        authModules = currentRefreshToken.getAuthModules();
        acr = currentRefreshToken.getAuthenticationContextClassReference();
    }
    OpenAMRefreshToken refreshToken = new OpenAMRefreshToken(id, resourceOwnerId, clientId, redirectUri, scope, expiryTime, OAuth2Constants.Bearer.BEARER, OAuth2Constants.Token.OAUTH_REFRESH_TOKEN, grantType, realm, authModules, acr, auditId);
    if (!StringUtils.isBlank(validatedClaims)) {
        refreshToken.setClaims(validatedClaims);
    }
    try {
        tokenStore.create(refreshToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logAccessMessage("CREATED_REFRESH_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_REFRESH_TOKEN", obs, null);
        }
        logger.error("Unable to create refresh token: " + refreshToken.getTokenInfo(), e);
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(RefreshToken.class, refreshToken);
    return refreshToken;
}
Also used : AuthorizationCode(org.forgerock.oauth2.core.AuthorizationCode) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) RefreshToken(org.forgerock.oauth2.core.RefreshToken) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 43 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class OpenAMTokenStore method createAccessToken.

/**
     * {@inheritDoc}
     */
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final AccessToken accessToken;
    if (refreshToken == null) {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    } else {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    }
    try {
        tokenStore.create(accessToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_TOKEN", accessToken.toString() };
            auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        logger.error("Could not create token in CTS: " + e.getMessage());
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
        }
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(AccessToken.class, accessToken);
    return accessToken;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 44 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class OpenAMTokenStore method deleteDeviceCode.

@Override
public void deleteDeviceCode(String clientId, String code, OAuth2Request request) throws ServerException, NotFoundException, InvalidGrantException {
    try {
        readDeviceCode(clientId, code, request);
        tokenStore.delete(code);
    } catch (CoreTokenException e) {
        throw new ServerException("Could not delete user code state");
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException)

Example 45 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class OpenAMTokenStore method createOpenIDToken.

/**
     * {@inheritDoc}
     */
public OpenIdConnectToken createOpenIDToken(ResourceOwner resourceOwner, String clientId, String authorizationParty, String nonce, String ops, OAuth2Request request) throws ServerException, InvalidClientException, NotFoundException {
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    OAuth2Uris oAuth2Uris = oauth2UrisFactory.get(request);
    final OpenIdConnectClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
    final String algorithm = clientRegistration.getIDTokenSignedResponseAlgorithm();
    final long currentTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    final long exp = TimeUnit.MILLISECONDS.toSeconds(clientRegistration.getJwtTokenLifeTime(providerSettings)) + currentTimeInSeconds;
    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    final String iss = oAuth2Uris.getIssuer();
    final List<String> amr = getAMRFromAuthModules(request, providerSettings);
    final byte[] clientSecret = clientRegistration.getClientSecret().getBytes(Utils.CHARSET);
    final KeyPair keyPair = providerSettings.getServerKeyPair();
    final String atHash = generateAtHash(algorithm, request, providerSettings);
    final String cHash = generateCHash(algorithm, request, providerSettings);
    final String acr = getAuthenticationContextClassReference(request);
    final String kid = generateKid(providerSettings.getJWKSet(), algorithm);
    final String opsId = UUID.randomUUID().toString();
    final long authTime = resourceOwner.getAuthTime();
    final String subId = clientRegistration.getSubValue(resourceOwner.getId(), providerSettings);
    try {
        tokenStore.create(json(object(field(OAuth2Constants.CoreTokenParams.ID, set(opsId)), field(OAuth2Constants.JWTTokenParams.LEGACY_OPS, set(ops)), field(OAuth2Constants.CoreTokenParams.EXPIRE_TIME, set(Long.toString(TimeUnit.SECONDS.toMillis(exp)))))));
    } catch (CoreTokenException e) {
        logger.error("Unable to create id_token user session token", e);
        throw new ServerException("Could not create token in CTS");
    }
    final OpenAMOpenIdConnectToken oidcToken = new OpenAMOpenIdConnectToken(kid, clientSecret, keyPair, algorithm, iss, subId, clientId, authorizationParty, exp, currentTimeInSeconds, authTime, nonce, opsId, atHash, cHash, acr, amr, realm);
    request.setSession(ops);
    //See spec section 5.4. - add claims to id_token based on 'response_type' parameter
    String responseType = request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE);
    if (providerSettings.isAlwaysAddClaimsToToken() || (responseType != null && responseType.trim().equals(OAuth2Constants.JWTTokenParams.ID_TOKEN))) {
        appendIdTokenClaims(request, providerSettings, oidcToken);
    } else if (providerSettings.getClaimsParameterSupported()) {
        appendRequestedIdTokenClaims(request, providerSettings, oidcToken);
    }
    return oidcToken;
}
Also used : OpenAMOpenIdConnectToken(org.forgerock.openam.openidconnect.OpenAMOpenIdConnectToken) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) KeyPair(java.security.KeyPair) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Aggregations

CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)59 JsonValue (org.forgerock.json.JsonValue)21 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)19 Token (org.forgerock.openam.cts.api.tokens.Token)14 Test (org.testng.annotations.Test)11 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)10 ResourceException (org.forgerock.json.resource.ResourceException)9 PartialToken (org.forgerock.openam.sm.datalayer.api.query.PartialToken)9 BadRequestException (org.forgerock.json.resource.BadRequestException)8 ArrayList (java.util.ArrayList)7 ResourceResponse (org.forgerock.json.resource.ResourceResponse)7 SSOException (com.iplanet.sso.SSOException)6 SSOToken (com.iplanet.sso.SSOToken)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 HashMap (java.util.HashMap)5 Responses.newResourceResponse (org.forgerock.json.resource.Responses.newResourceResponse)5 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)5 TokenFilter (org.forgerock.openam.cts.api.filter.TokenFilter)5 TokenFilterBuilder (org.forgerock.openam.cts.api.filter.TokenFilterBuilder)5 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)5