Search in sources :

Example 46 with CoreTokenException

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

the class OpenAMTokenStore method readDeviceCode.

@Override
public DeviceCode readDeviceCode(String clientId, String code, OAuth2Request request) throws ServerException, NotFoundException, InvalidGrantException {
    DeviceCode deviceCode = request.getToken(DeviceCode.class);
    if (deviceCode == null) {
        try {
            JsonValue token = tokenStore.read(code);
            if (token == null) {
                return null;
            }
            deviceCode = new DeviceCode(token);
        } catch (CoreTokenException e) {
            logger.error("Unable to read device code corresponding to id: " + code, e);
            throw new ServerException("Could not read token in CTS: " + e.getMessage());
        }
    }
    if (!clientId.equals(deviceCode.getClientId())) {
        throw new InvalidGrantException();
    }
    validateTokenRealm(deviceCode.getRealm(), request);
    request.setToken(DeviceCode.class, deviceCode);
    return deviceCode;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JsonValue(org.forgerock.json.JsonValue) DeviceCode(org.forgerock.oauth2.core.DeviceCode) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 47 with CoreTokenException

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

the class OAuth2UserApplications method deleteInstance.

/**
     * Allows users to revoke an OAuth2 application. This will remove their consent and revoke any access and refresh
     * tokens with a matching client id.
     * @param context The request context.
     * @param resourceId The id of the OAuth2 client.
     * @return A promise of the removed application.
     */
@Delete
public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId) {
    String userId = contextHelper.getUserId(context);
    String realm = contextHelper.getRealm(context);
    debug.message("Revoking access to OAuth2 client {} for user {}", resourceId, userId);
    try {
        oAuth2ProviderSettingsFactory.get(context).revokeConsent(userId, resourceId);
        QueryFilter<CoreTokenField> queryFilter = and(getQueryFilter(userId, realm), equalTo(CLIENT_ID.getField(), resourceId));
        JsonValue tokens = tokenStore.query(queryFilter);
        if (tokens.asCollection().isEmpty()) {
            return new org.forgerock.json.resource.NotFoundException().asPromise();
        }
        for (JsonValue token : tokens) {
            String tokenId = getAttributeValue(token, ID.getOAuthField());
            debug.message("Removing OAuth2 token {} with client {} for user {}", tokenId, resourceId, userId);
            tokenStore.delete(tokenId);
        }
        return getResourceResponse(context, resourceId, tokens).asPromise();
    } catch (CoreTokenException | InvalidClientException | NotFoundException | ServerException e) {
        debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
        return new InternalServerErrorException(e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
        return e.asPromise();
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) 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) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Delete(org.forgerock.json.resource.annotations.Delete)

Example 48 with CoreTokenException

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

the class TokenResource method queryCollection.

@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
    try {
        JsonValue response;
        Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
        //get uid of submitter
        AMIdentity uid;
        try {
            uid = getUid(context);
            if (!uid.equals(adminUserId)) {
                query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
                query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
            }
        } catch (Exception e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
            }
            return new PermanentException(401, "Unauthorized", e).asPromise();
        }
        String id = queryRequest.getQueryId();
        String queryString;
        if (id.equals("access_token")) {
            queryString = "tokenName=access_token";
        } else {
            queryString = id;
        }
        String[] constraints = queryString.split(",");
        boolean userNamePresent = false;
        for (String constraint : constraints) {
            String[] params = constraint.split("=");
            if (params.length == 2) {
                if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
                    userNamePresent = true;
                }
                query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
            }
        }
        if (adminUserId.equals(uid)) {
            if (!userNamePresent) {
                return new BadRequestException("userName field MUST be set in _queryId").asPromise();
            }
        } else if (userNamePresent) {
            return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
        }
        response = tokenStore.query(QueryFilter.and(query));
        return handleResponse(handler, response, context);
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, e.getMessage(), e).asPromise();
    } catch (CoreTokenException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
        return e.asPromise();
    } catch (NotFoundException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
        return e.asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) QueryFilter(org.forgerock.util.query.QueryFilter) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 49 with CoreTokenException

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

the class TokenResource method readInstance.

@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue response;
        ResourceResponse resource;
        try {
            response = tokenStore.read(resourceId);
        } catch (CoreTokenException e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID", e);
        }
        if (response == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID");
        }
        JsonValue expireTimeValue = response.get(OAuth2Constants.CoreTokenParams.EXPIRE_TIME);
        long expireTime;
        if (expireTimeValue.isNumber()) {
            expireTime = expireTimeValue.asLong();
        } else {
            Set<String> expireTimeSet = (Set<String>) expireTimeValue.getObject();
            expireTime = Long.parseLong(expireTimeSet.iterator().next());
        }
        if (System.currentTimeMillis() > expireTime) {
            throw new NotFoundException("Could not find valid token with given ID");
        }
        String grantType = getAttributeValue(response, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS)) {
            resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
            return newResultPromise(resource);
        } else {
            String realm = getAttributeValue(response, REALM);
            String username = getAttributeValue(response, USERNAME);
            if (username == null || username.isEmpty()) {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
                }
                throw new NotFoundException("Could not find valid token with given ID");
            }
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(adminUserId) || uid.equals(uid2)) {
                resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
                return newResultPromise(resource);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : Only the resource owner or an administrator may perform " + "a read on the token with ID, " + resourceId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : Set(java.util.Set) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 50 with CoreTokenException

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

the class OpenAMOpenIDConnectProvider method destroySession.

/**
     * {@inheritDoc}
     */
public void destroySession(String opsId) throws ServerException {
    try {
        final Token opsToken = cts.read(opsId);
        if (opsToken == null) {
            throw new CoreTokenException("Unable to find id_token");
        }
        JsonValue idTokenUserSessionToken = tokenAdapter.fromToken(opsToken);
        cts.delete(opsId);
        String sessionId = idTokenUserSessionToken.get(OAuth2Constants.JWTTokenParams.LEGACY_OPS).asSet(String.class).iterator().next();
        // for some grant type, there is no OpenAM session associated with a id_token
        if (sessionId != null) {
            final SSOToken token = tokenManager.createSSOToken(sessionId);
            tokenManager.destroyToken(token);
        }
    } catch (CoreTokenException e) {
        logger.error("Unable to get id_token meta data", e);
        throw new ServerException("Unable to get id_token meta data");
    } catch (Exception e) {
        logger.error("Unable to get SsoTokenManager", e);
        throw new ServerException("Unable to get SsoTokenManager");
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Token(org.forgerock.openam.cts.api.tokens.Token) SSOToken(com.iplanet.sso.SSOToken) 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