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();
}
}
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);
}
}
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);
}
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();
}
}
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);
}
Aggregations