use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.
the class UmaPolicyServiceImpl method queryPolicies.
/**
* {@inheritDoc}
*/
@Override
public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> queryPolicies(final Context context, final QueryRequest umaQueryRequest) {
if (umaQueryRequest.getQueryExpression() != null) {
return new BadRequestException("Query expressions not supported").asPromise();
}
QueryRequest request = Requests.newQueryRequest("");
final AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>> filter = umaQueryRequest.getQueryFilter().accept(new AggregateUmaPolicyQueryFilter(), new AggregateQuery<QueryFilter<JsonPointer>, QueryFilter<JsonPointer>>());
String queryId = umaQueryRequest.getQueryId();
if (queryId != null && queryId.equals("searchAll")) {
request.setQueryFilter(QueryFilter.<JsonPointer>alwaysTrue());
} else {
String resourceOwnerUid = getResourceOwnerUid(context);
if (filter.getFirstQuery() == null) {
request.setQueryFilter(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid));
} else {
request.setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("createdBy"), resourceOwnerUid), filter.getFirstQuery()));
}
}
return policyResourceDelegate.queryPolicies(context, request).thenAsync(new AsyncFunction<Pair<QueryResponse, List<ResourceResponse>>, Collection<UmaPolicy>, ResourceException>() {
@Override
public Promise<Collection<UmaPolicy>, ResourceException> apply(Pair<QueryResponse, List<ResourceResponse>> value) {
Map<String, Set<ResourceResponse>> policyMapping = new HashMap<>();
for (ResourceResponse policy : value.getSecond()) {
String resource = policy.getContent().get("resources").asList(String.class).get(0);
if (!resource.startsWith(UMA_POLICY_SCHEME)) {
continue;
}
resource = resource.replaceFirst(UMA_POLICY_SCHEME, "");
if (resource.indexOf(":") > 0) {
resource = resource.substring(0, resource.indexOf(":"));
}
Set<ResourceResponse> mapping = policyMapping.get(resource);
if (mapping == null) {
mapping = new HashSet<>();
policyMapping.put(resource, mapping);
}
mapping.add(policy);
}
try {
Collection<UmaPolicy> umaPolicies = new HashSet<>();
for (Map.Entry<String, Set<ResourceResponse>> entry : policyMapping.entrySet()) {
ResourceSetDescription resourceSet = getResourceSetDescription(entry.getKey(), context);
UmaPolicy umaPolicy = UmaPolicy.fromUnderlyingPolicies(resourceSet, entry.getValue());
resolveUIDToUsername(umaPolicy.asJson());
umaPolicies.add(umaPolicy);
}
return newResultPromise(umaPolicies);
} catch (ResourceException e) {
return e.asPromise();
}
}
}).thenAsync(new AsyncFunction<Collection<UmaPolicy>, Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException>() {
@Override
public Promise<Pair<QueryResponse, Collection<UmaPolicy>>, ResourceException> apply(Collection<UmaPolicy> policies) {
Collection<UmaPolicy> results = policies;
if (filter.getSecondQuery() != null) {
PolicySearch search = filter.getSecondQuery().accept(new UmaPolicyQueryFilterVisitor(), new PolicySearch(policies));
if (AggregateQuery.Operator.AND.equals(filter.getOperator())) {
results.retainAll(search.getPolicies());
}
}
int pageSize = umaQueryRequest.getPageSize();
String pagedResultsCookie = umaQueryRequest.getPagedResultsCookie();
int pagedResultsOffset = umaQueryRequest.getPagedResultsOffset();
Collection<UmaPolicy> pagedPolicies = new HashSet<UmaPolicy>();
int count = 0;
for (UmaPolicy policy : results) {
if (count >= pagedResultsOffset * pageSize) {
pagedPolicies.add(policy);
}
count++;
}
int remainingPagedResults = results.size() - pagedPolicies.size();
if (pageSize > 0) {
remainingPagedResults /= pageSize;
}
return newResultPromise(Pair.of(newQueryResponse(pagedResultsCookie, CountPolicy.EXACT, remainingPagedResults), pagedPolicies));
}
});
}
use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.
the class AuthorizationServiceImpl method authorize.
/**
* {@inheritDoc}
*/
public AuthorizationToken authorize(OAuth2Request request) throws ResourceOwnerAuthenticationRequired, ResourceOwnerConsentRequired, InvalidClientException, UnsupportedResponseTypeException, RedirectUriMismatchException, InvalidRequestException, AccessDeniedException, ServerException, LoginRequiredException, BadRequestException, InteractionRequiredException, ResourceOwnerConsentRequiredException, InvalidScopeException, NotFoundException {
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
for (final AuthorizeRequestValidator requestValidator : requestValidators) {
requestValidator.validateRequest(request);
}
final String clientId = request.getParameter(CLIENT_ID);
final ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
final Set<String> scope = Utils.splitScope(request.<String>getParameter(SCOPE));
//plugin point
final Set<String> validatedScope = providerSettings.validateAuthorizationScope(clientRegistration, scope, request);
// is resource owner authenticated?
final ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
final boolean consentSaved = providerSettings.isConsentSaved(resourceOwner, clientRegistration.getClientId(), validatedScope);
//plugin point
final boolean haveConsent = consentVerifier.verify(consentSaved, request, clientRegistration);
if (!haveConsent) {
String localeParameter = request.getParameter(LOCALE);
String uiLocaleParameter = request.getParameter(UI_LOCALES);
Locale locale = getLocale(uiLocaleParameter, localeParameter);
if (locale == null) {
locale = request.getLocale();
}
UserInfoClaims userInfo = null;
try {
userInfo = providerSettings.getUserInfo(request.getToken(AccessToken.class), request);
} catch (UnauthorizedClientException e) {
logger.debug("Couldn't get user info - continuing to display consent page without claims.", e);
}
String clientName = clientRegistration.getDisplayName(locale);
if (clientName == null) {
clientName = clientRegistration.getClientId();
logger.warn("Client does not have a display name or client name set. using client ID {} for display", clientName);
}
final String displayDescription = clientRegistration.getDisplayDescription(locale);
final String clientDescription = displayDescription == null ? "" : displayDescription;
final Map<String, String> scopeDescriptions = getScopeDescriptions(validatedScope, clientRegistration.getScopeDescriptions(locale));
final Map<String, String> claimDescriptions = getClaimDescriptions(userInfo.getValues(), clientRegistration.getClaimDescriptions(locale));
throw new ResourceOwnerConsentRequired(clientName, clientDescription, scopeDescriptions, claimDescriptions, userInfo, resourceOwner.getName(providerSettings));
}
return tokenIssuer.issueTokens(request, clientRegistration, resourceOwner, scope, providerSettings);
}
use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.
the class TokenInfoServiceImpl method getTokenInfo.
/**
* {@inheritDoc}
*/
public JsonValue getTokenInfo(OAuth2Request request) throws InvalidTokenException, InvalidRequestException, ExpiredTokenException, ServerException, BadRequestException, InvalidGrantException, NotFoundException {
final AccessTokenVerifier.TokenState headerToken = headerTokenVerifier.verify(request);
final AccessTokenVerifier.TokenState queryToken = queryTokenVerifier.verify(request);
final Map<String, Object> response = new HashMap<String, Object>();
if (!headerToken.isValid() && !queryToken.isValid()) {
logger.error("Access Token not valid");
throw new InvalidRequestException("Access Token not valid");
} else if (headerToken.isValid() && queryToken.isValid()) {
logger.error("Access Token provided in both query and header in request");
throw new InvalidRequestException("Access Token cannot be provided in both query and header");
} else {
final AccessToken accessToken = request.getToken(AccessToken.class);
logger.trace("In Validator resource - got token = " + accessToken);
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final Map<String, Object> scopeEvaluation = providerSettings.evaluateScope(accessToken);
response.putAll(accessToken.getTokenInfo());
response.putAll(scopeEvaluation);
return new JsonValue(response);
}
}
use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.
the class AuthorizationRequestEndpoint method getTicketId.
private String getTicketId(JsonValue requestBody) throws BadRequestException {
final JsonValue ticket = requestBody.get("ticket");
String ticketId = null;
try {
ticketId = ticket.asString();
} catch (Exception e) {
throw new BadRequestException(UNABLE_TO_RETRIEVE_TICKET_MESSAGE);
}
if (ticketId == null) {
throw new BadRequestException(UNABLE_TO_RETRIEVE_TICKET_MESSAGE);
}
return ticketId;
}
use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.
the class OpenIdConnectAuthorizeRequestValidator method validateRequest.
/**
* {@inheritDoc}
*/
public void validateRequest(OAuth2Request request) throws BadRequestException, InvalidRequestException, InvalidClientException, InvalidScopeException, NotFoundException {
validateOpenIdScope(request);
try {
OpenIdPrompt prompt = new OpenIdPrompt(request);
Reject.ifFalse(prompt.isValid(), "Prompt parameter " + prompt.getOriginalValue() + " is invalid or unsupported");
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
}
Aggregations