Search in sources :

Example 1 with CoreTokenException

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

the class AsyncResultHandlerTest method shouldThrowExceptionProvided.

@Test
public void shouldThrowExceptionProvided() {
    handler.processError(new CoreTokenException("Test"));
    assertThat(await(handler)).isInstanceOfAny(Throwable.class);
}
Also used : CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Test(org.testng.annotations.Test)

Example 2 with CoreTokenException

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

the class CTSTokenPersistenceImpl method persistToken.

@Override
public void persistToken(String stsId, TokenType tokenType, String tokenString, String subjectId, long issueInstantMillis, long tokenLifetimeSeconds) throws CTSTokenPersistenceException {
    try {
        final String tokenId = ctsTokenIdGenerator.generateTokenId(tokenType, tokenString);
        final Token ctsToken = generateToken(stsId, tokenString.getBytes(AMSTSConstants.UTF_8_CHARSET_ID), tokenId, subjectId, issueInstantMillis, tokenLifetimeSeconds, tokenType);
        ctsPersistentStore.create(ctsToken);
    } catch (TokenIdGenerationException e) {
        throw new CTSTokenPersistenceException(e.getCode(), "Exception caught generating id for CTS-persisted " + tokenType + "  token: " + e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new CTSTokenPersistenceException(ResourceException.INTERNAL_ERROR, "Exception caught getting byte[] " + "representation of issued " + tokenType + " token for CTS persistence: " + e, e);
    } catch (CoreTokenException e) {
        throw new CTSTokenPersistenceException(ResourceException.INTERNAL_ERROR, "Exception caught persisting issued " + tokenType + " token in the CTS: " + e.getMessage(), e);
    }
}
Also used : TokenIdGenerationException(org.forgerock.openam.sts.TokenIdGenerationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Token(org.forgerock.openam.cts.api.tokens.Token) PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) CTSTokenPersistenceException(org.forgerock.openam.sts.CTSTokenPersistenceException)

Example 3 with CoreTokenException

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

the class TokenResource method deleteToken.

/**
     * Deletes the token with the provided token id.
     *
     * @param context The context.
     * @param tokenId The token id.
     * @param deleteRefreshToken Whether to delete associated refresh token, if token id is for an access token.
     * @return {@code Void} if the token has been deleted.
     */
private Promise<Void, ResourceException> deleteToken(Context context, String tokenId, boolean deleteRefreshToken) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue token = tokenStore.read(tokenId);
        if (token == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No token with ID, " + tokenId + " found to delete");
            }
            throw new NotFoundException("Token Not Found", null);
        }
        String username = getAttributeValue(token, USERNAME);
        if (username == null || username.isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No username associated with " + "token with ID, " + tokenId + ".");
            }
            throw new PermanentException(HttpURLConnection.HTTP_NOT_FOUND, "Not Found", null);
        }
        String grantType = getAttributeValue(token, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(CLIENT_CREDENTIALS)) {
            if (deleteRefreshToken) {
                deleteAccessTokensRefreshToken(token);
            }
            tokenStore.delete(tokenId);
        } else {
            String realm = getAttributeValue(token, REALM);
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(uid2) || uid.equals(adminUserId)) {
                if (deleteRefreshToken) {
                    deleteAccessTokensRefreshToken(token);
                }
                tokenStore.delete(tokenId);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: DELETE : Only the resource owner or an administrator may perform " + "a delete on the token with ID, " + tokenId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
        return newResultPromise(null);
    } catch (CoreTokenException e) {
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: DELETE : Requesting user is unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException)

Example 4 with CoreTokenException

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

the class OAuth2UserApplications method query.

/**
     * Allows users to query OAuth2 applications that they have given their consent access to and that have active
     * access and/or refresh tokens.
     *
     * <p>Applications consist of an id, a name (the client id), a set of scopes and an expiry time. The scopes field
     * is the union of the scopes of the individual access/refresh tokens. The expiry time is the time when the last
     * access/refresh token will expire, or null if the server is configured to allow tokens to be refreshed
     * indefinitely.</p>
     *
     * @param context The request context.
     * @param queryHandler The query handler.
     * @param request Unused but necessary for used of the {@link @Query} annotation.
     * @return A promise of a query response.
     */
@Query
public Promise<QueryResponse, ResourceException> query(Context context, QueryResourceHandler queryHandler, QueryRequest request) {
    String userId = contextHelper.getUserId(context);
    String realm = contextHelper.getRealm(context);
    try {
        QueryFilter<CoreTokenField> queryFilter = getQueryFilter(userId, realm);
        JsonValue tokens = tokenStore.query(queryFilter);
        Map<String, Set<JsonValue>> applicationTokensMap = new HashMap<>();
        for (JsonValue token : tokens) {
            String clientId = getAttributeValue(token, CLIENT_ID.getOAuthField());
            Set<JsonValue> applicationTokens = applicationTokensMap.get(clientId);
            if (applicationTokens == null) {
                applicationTokens = new HashSet<>();
                applicationTokensMap.put(clientId, applicationTokens);
            }
            applicationTokens.add(token);
        }
        for (Map.Entry<String, Set<JsonValue>> applicationTokens : applicationTokensMap.entrySet()) {
            ResourceResponse resource = getResourceResponse(context, applicationTokens.getKey(), applicationTokens.getValue());
            queryHandler.handleResource(resource);
        }
        return Promises.newResultPromise(Responses.newQueryResponse());
    } catch (CoreTokenException | ServerException | InvalidClientException | NotFoundException e) {
        debug.message("Failed to query OAuth2 clients for user {}", userId, e);
        return new InternalServerErrorException(e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.message("Failed to query OAuth2 clients for user {}", userId, e);
        return e.asPromise();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ResourceResponse(org.forgerock.json.resource.ResourceResponse) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) HashMap(java.util.HashMap) Map(java.util.Map) Query(org.forgerock.json.resource.annotations.Query)

Example 5 with CoreTokenException

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

the class UmaTokenStore method createPermissionTicket.

PermissionTicket createPermissionTicket(String resourceSetId, Set<String> scopes, String clientId) throws ServerException, NotFoundException {
    UmaProviderSettings settings = settingsFactory.get(realm);
    PermissionTicket permissionTicket = new PermissionTicket(null, resourceSetId, scopes, clientId);
    permissionTicket.setRealm(realm);
    permissionTicket.setExpiryTime(System.currentTimeMillis() + (settings.getPermissionTicketLifetime() * 1000));
    try {
        cts.create(permissionTicketAdapter.toToken(permissionTicket));
    } catch (CoreTokenException e) {
        throw new ServerException(e);
    }
    return permissionTicket;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException)

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