Search in sources :

Example 11 with BadRequestException

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));
        }
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) JsonPointer(org.forgerock.json.JsonPointer) AsyncFunction(org.forgerock.util.AsyncFunction) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) List(java.util.List) ArrayList(java.util.ArrayList) ResourceException(org.forgerock.json.resource.ResourceException) PolicySearch(org.forgerock.openam.uma.PolicySearch) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) HashSet(java.util.HashSet) UmaPolicyQueryFilterVisitor(org.forgerock.openam.uma.UmaPolicyQueryFilterVisitor) QueryRequest(org.forgerock.json.resource.QueryRequest) Promise(org.forgerock.util.promise.Promise) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceResponse(org.forgerock.json.resource.ResourceResponse) Responses.newQueryResponse(org.forgerock.json.resource.Responses.newQueryResponse) QueryResponse(org.forgerock.json.resource.QueryResponse) BadRequestException(org.forgerock.json.resource.BadRequestException) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with BadRequestException

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);
}
Also used : Locale(java.util.Locale) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) ResourceOwnerConsentRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerConsentRequired)

Example 13 with BadRequestException

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);
    }
}
Also used : HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) HashMap(java.util.HashMap) Map(java.util.Map) AccessTokenVerifier(org.forgerock.oauth2.core.AccessTokenVerifier)

Example 14 with BadRequestException

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;
}
Also used : JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) JSONException(org.json.JSONException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) EntitlementException(com.sun.identity.entitlement.EntitlementException)

Example 15 with BadRequestException

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());
    }
}
Also used : BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException)

Aggregations

BadRequestException (org.forgerock.oauth2.core.exceptions.BadRequestException)8 JsonValue (org.forgerock.json.JsonValue)7 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)7 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)6 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)5 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)5 HashMap (java.util.HashMap)4 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)4 Test (org.testng.annotations.Test)4 AMIdentity (com.sun.identity.idm.AMIdentity)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 BadRequestException (org.forgerock.json.resource.BadRequestException)3 ResourceException (org.forgerock.json.resource.ResourceException)3 InvalidRequestException (org.forgerock.oauth2.core.exceptions.InvalidRequestException)3 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)3 SSOException (com.iplanet.sso.SSOException)2 HashSet (java.util.HashSet)2 List (java.util.List)2 ResourceResponse (org.forgerock.json.resource.ResourceResponse)2