Search in sources :

Example 41 with JsonValue

use of org.forgerock.json.JsonValue 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 42 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class TokenResource method getExpiryDate.

private String getExpiryDate(JsonValue token, Context context) throws CoreTokenException, InternalServerErrorException, NotFoundException {
    OAuth2ProviderSettings oAuth2ProviderSettings;
    final String realm = getAttributeValue(token, "realm");
    try {
        oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(realm);
    } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
        throw new NotFoundException(e.getMessage());
    }
    try {
        if (token.isDefined("refreshToken")) {
            if (oAuth2ProviderSettings.issueRefreshTokensOnRefreshingToken()) {
                return getIndefinitelyString(context);
            } else {
                //Use refresh token expiry
                JsonValue refreshToken = tokenStore.read(getAttributeValue(token, "refreshToken"));
                long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(refreshToken, EXPIRE_TIME_KEY));
                if (expiryTimeInMilliseconds == -1) {
                    return getIndefinitelyString(context);
                }
                return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
            }
        } else {
            //Use access token expiry
            long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(token, EXPIRE_TIME_KEY));
            return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
        }
    } catch (ServerException | SMSException | SSOException e) {
        throw new InternalServerErrorException(e);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) Date(java.util.Date) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 43 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class OpenAMTokenStoreTest method shouldReadAccessToken.

@Test
public void shouldReadAccessToken() throws Exception {
    //Given
    JsonValue token = json(object(field("tokenName", Collections.singleton("access_token")), field("realm", Collections.singleton("/testrealm"))));
    given(tokenStore.read("TOKEN_ID")).willReturn(token);
    ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
    attributes.put("realm", "/testrealm");
    given(request.getAttributes()).willReturn(attributes);
    given(realmNormaliser.normalise("/testrealm")).willReturn("/testrealm");
    OAuth2Request request = oAuth2RequestFactory.create(this.request);
    //When
    AccessToken accessToken = openAMtokenStore.readAccessToken(request, "TOKEN_ID");
    //Then
    assertThat(accessToken).isNotNull();
    assertThat(request.getToken(AccessToken.class)).isSameAs(accessToken);
}
Also used : RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AccessToken(org.forgerock.oauth2.core.AccessToken) JsonValue(org.forgerock.json.JsonValue) BDDMockito.anyString(org.mockito.BDDMockito.anyString) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test)

Example 44 with JsonValue

use of org.forgerock.json.JsonValue 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 45 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpoint method updateResourceSet.

@Put
public Representation updateResourceSet(JsonRepresentation entity) throws NotFoundException, ServerException, BadRequestException {
    if (!isConditionalRequest()) {
        throw new ResourceException(512, "precondition_failed", "Require If-Match header to update Resource Set", null);
    }
    final Map<String, Object> resourceSetDescriptionAttributes = validator.validate(toMap(entity));
    final String resourceSetId = getResourceSetId();
    ResourceSetStore store = providerSettingsFactory.get(requestFactory.create(getRequest())).getResourceSetStore();
    ResourceSetDescription resourceSetDescription = store.read(resourceSetId, getResourceOwnerId()).update(resourceSetDescriptionAttributes);
    JsonValue labels = resourceSetDescription.getDescription().get(OAuth2Constants.ResourceSets.LABELS);
    resourceSetDescription.getDescription().remove(OAuth2Constants.ResourceSets.LABELS);
    store.update(resourceSetDescription);
    if (labels.isNotNull()) {
        resourceSetDescription.getDescription().add(OAuth2Constants.ResourceSets.LABELS, labels.asSet());
    } else {
        resourceSetDescription.getDescription().add(OAuth2Constants.ResourceSets.LABELS, new HashSet<String>());
    }
    labelRegistration.updateLabelsForExistingResourceSet(resourceSetDescription);
    return createJsonResponse(resourceSetDescription, false, true);
}
Also used : ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) JsonValue(org.forgerock.json.JsonValue) ResourceException(org.restlet.resource.ResourceException) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Put(org.restlet.resource.Put)

Aggregations

JsonValue (org.forgerock.json.JsonValue)575 Test (org.testng.annotations.Test)333 ResourceException (org.forgerock.json.resource.ResourceException)144 ResourceResponse (org.forgerock.json.resource.ResourceResponse)123 RealmContext (org.forgerock.openam.rest.RealmContext)70 Context (org.forgerock.services.context.Context)63 HashSet (java.util.HashSet)56 SSOException (com.iplanet.sso.SSOException)54 ArrayList (java.util.ArrayList)51 BadRequestException (org.forgerock.json.resource.BadRequestException)47 Privilege (com.sun.identity.entitlement.Privilege)46 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)46 SSOToken (com.iplanet.sso.SSOToken)43 SMSException (com.sun.identity.sm.SMSException)42 HashMap (java.util.HashMap)42 NotFoundException (org.forgerock.json.resource.NotFoundException)41 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)41 CreateRequest (org.forgerock.json.resource.CreateRequest)40 OpenSSOPrivilege (com.sun.identity.entitlement.opensso.OpenSSOPrivilege)39 Subject (javax.security.auth.Subject)32