Search in sources :

Example 16 with BadRequestException

use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.

the class ClaimsParameterValidatorTest method shouldValidateClaimsParameter.

@Test
public void shouldValidateClaimsParameter() throws NotFoundException, BadRequestException, RedirectUriMismatchException, InvalidScopeException, InvalidRequestException, InvalidClientException, ServerException, UnsupportedResponseTypeException {
    //given
    OAuth2Request mockRequest = mock(OAuth2Request.class);
    OAuth2ProviderSettings mockProviderSettings = mock(OAuth2ProviderSettings.class);
    String responseTypes = "code token id_token";
    given(mockProviderSettingsFactory.get(mockRequest)).willReturn(mockProviderSettings);
    given(mockProviderSettings.getClaimsParameterSupported()).willReturn(true);
    given(mockRequest.getParameter(OAuth2Constants.Custom.CLAIMS)).willReturn(validClaimsString);
    given(mockRequest.getParameter(OAuth2Constants.Params.RESPONSE_TYPE)).willReturn(responseTypes);
    //when
    claimsParameterValidator.validateRequest(mockRequest);
//then
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 17 with BadRequestException

use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.

the class OpenAMResourceSetStore method create.

@Override
public void create(OAuth2Request request, ResourceSetDescription resourceSetDescription) throws ServerException, BadRequestException, NotFoundException {
    resourceSetDescription.setId(idGenerator.generateTokenId(null));
    String policyEndpoint = oauth2UrisFactory.get(request).getResourceSetRegistrationPolicyEndpoint(resourceSetDescription.getId());
    resourceSetDescription.setPolicyUri(policyEndpoint);
    resourceSetDescription.setRealm(realm);
    try {
        delegate.create(resourceSetDescription);
    } catch (org.forgerock.openam.sm.datalayer.store.ServerException e) {
        throw new ServerException(e);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException)

Example 18 with BadRequestException

use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpoint method createResourceSet.

/**
     * <p>Creates or updates a resource set description.</p>
     *
     * <p>If the request contains a If-Match header an update is performed, otherwise a create is performed.</p>
     *
     * <p>An update will replace the current description of the resource set with the contents of the request body.</p>
     *
     * @param entity The new resource set description.
     * @return A JSON object containing the authorization server's unique id for the resource set and, optionally,
     * a policy uri.
     * @throws NotFoundException If the requested resource set description does not exist.
     * @throws ServerException When an error occurs during creating or updating.
     * @throws BadRequestException If the request JSON is invalid.
     */
@Post
public Representation createResourceSet(JsonRepresentation entity) throws NotFoundException, ServerException, BadRequestException {
    ResourceSetDescription resourceSetDescription = new ResourceSetDescription(null, getClientId(), getResourceOwnerId(), validator.validate(toMap(entity)));
    OAuth2Request oAuth2Request = requestFactory.create(getRequest());
    ResourceSetStore store = providerSettingsFactory.get(oAuth2Request).getResourceSetStore();
    QueryFilter<String> query = QueryFilter.and(QueryFilter.equalTo(ResourceSetTokenField.NAME, resourceSetDescription.getName()), QueryFilter.equalTo(ResourceSetTokenField.CLIENT_ID, getClientId()), QueryFilter.equalTo(ResourceSetTokenField.RESOURCE_OWNER_ID, getResourceOwnerId()));
    if (!store.query(query).isEmpty()) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        Map<String, Object> response = new HashMap<String, Object>();
        response.put(OAuth2Constants.Params.ERROR, Status.CLIENT_ERROR_BAD_REQUEST.getReasonPhrase());
        response.put(OAuth2Constants.Params.ERROR_DESCRIPTION, "A shared item with the name '" + resourceSetDescription.getName() + "' already exists");
        return new JsonRepresentation(response);
    }
    JsonValue labels = resourceSetDescription.getDescription().get(OAuth2Constants.ResourceSets.LABELS);
    resourceSetDescription.getDescription().remove(OAuth2Constants.ResourceSets.LABELS);
    for (ResourceRegistrationFilter filter : extensionFilterManager.getFilters(ResourceRegistrationFilter.class)) {
        filter.beforeResourceRegistration(resourceSetDescription);
    }
    store.create(oAuth2Request, resourceSetDescription);
    if (labels.isNotNull()) {
        resourceSetDescription.getDescription().add(OAuth2Constants.ResourceSets.LABELS, labels.asSet());
    }
    labelRegistration.updateLabelsForNewResourceSet(resourceSetDescription);
    for (ResourceRegistrationFilter filter : extensionFilterManager.getFilters(ResourceRegistrationFilter.class)) {
        filter.afterResourceRegistration(resourceSetDescription);
    }
    for (ResourceSetRegistrationHook hook : hooks) {
        hook.resourceSetCreated(oAuth2Request.<String>getParameter("realm"), resourceSetDescription);
    }
    getResponse().setStatus(Status.SUCCESS_CREATED);
    return createJsonResponse(resourceSetDescription, false, true);
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) HashMap(java.util.HashMap) ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) ResourceSetRegistrationHook(org.forgerock.oauth2.restlet.resources.ResourceSetRegistrationHook) JsonValue(org.forgerock.json.JsonValue) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) ResourceRegistrationFilter(org.forgerock.openam.oauth2.extensions.ResourceRegistrationFilter) Post(org.restlet.resource.Post)

Example 19 with BadRequestException

use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.

the class DeviceCodeVerificationResource method saveConsent.

private void saveConsent(OAuth2Request request) throws NotFoundException, ServerException, InvalidScopeException, AccessDeniedException, ResourceOwnerAuthenticationRequired, InteractionRequiredException, BadRequestException, LoginRequiredException, InvalidClientException {
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
    ClientRegistration clientRegistration = clientRegistrationStore.get(request.<String>getParameter(CLIENT_ID), request);
    Set<String> scope = Utils.splitScope(request.<String>getParameter(SCOPE));
    Set<String> validatedScope = providerSettings.validateAuthorizationScope(clientRegistration, scope, request);
    providerSettings.saveConsent(resourceOwner, clientRegistration.getClientId(), validatedScope);
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 20 with BadRequestException

use of org.forgerock.oauth2.core.exceptions.BadRequestException in project OpenAM by OpenRock.

the class OpenAMResourceOwnerSessionValidator method validate.

/**
     * {@inheritDoc}
     */
public ResourceOwner validate(OAuth2Request request) throws ResourceOwnerAuthenticationRequired, AccessDeniedException, BadRequestException, InteractionRequiredException, LoginRequiredException, ServerException, NotFoundException {
    final OpenIdPrompt openIdPrompt = new OpenIdPrompt(request);
    if (!openIdPrompt.isValid()) {
        String message = "Invalid prompt parameter \"" + openIdPrompt.getOriginalValue() + "\"";
        logger.message(message);
        throw new BadRequestException(message);
    }
    SSOToken token = null;
    try {
        token = ssoTokenManager.createSSOToken(getHttpServletRequest(request.<Request>getRequest()));
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token == null) {
            token = ssoTokenManager.createSSOToken(request.getSession());
        }
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token != null) {
            try {
                // As the organization in the token is stored in lowercase, we need to lower case the auth2realm
                String auth2Realm = dnWrapper.orgNameToDN(realmNormaliser.normalise((String) request.getParameter("realm"))).toLowerCase();
                String tokenRealm = token.getProperty("Organization");
                // auth2Realm can't be null as we would have an error earlier
                if (!auth2Realm.equals(tokenRealm)) {
                    throw authenticationRequired(request);
                }
            } catch (SSOException e) {
                throw new AccessDeniedException(e);
            }
            if (openIdPrompt.containsLogin()) {
                throw authenticationRequired(request, token);
            }
            final String acrValuesStr = request.getParameter(ACR_VALUES);
            if (acrValuesStr != null) {
                setCurrentAcr(token, request, acrValuesStr);
            }
            try {
                final long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
                if (isPastMaxAge(getMaxAge(request), authTime)) {
                    alterMaxAge(request);
                    throw authenticationRequired(request, token);
                }
                final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
                return new OpenAMResourceOwner(id.getName(), id, authTime);
            } catch (Exception e) {
                //Exception as chance of MANY exception types here.
                logger.error("Error authenticating user against OpenAM: ", e);
                throw new LoginRequiredException();
            }
        } else if (PASSWORD.equals(request.getParameter(GRANT_TYPE))) {
            // been null from the attempted creation in L148.
            return getResourceOwner(request.getToken(AccessToken.class));
        } else {
            if (openIdPrompt.containsNone()) {
                logger.error("Not pre-authenticated and prompt parameter equals none.");
                if (request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE) != null) {
                    throw new InteractionRequiredException(Utils.isOpenIdConnectFragmentErrorType(splitResponseType(request.<String>getParameter(RESPONSE_TYPE))) ? FRAGMENT : QUERY);
                } else {
                    throw new InteractionRequiredException();
                }
            } else if (!isRefreshToken(request)) {
                throw authenticationRequired(request);
            } else {
                return getResourceOwner(request.getToken(RefreshToken.class));
            }
        }
    } catch (SSOException | UnsupportedEncodingException | URISyntaxException e) {
        throw new AccessDeniedException(e);
    }
}
Also used : LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) SSOToken(com.iplanet.sso.SSOToken) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSOException(com.iplanet.sso.SSOException) URISyntaxException(java.net.URISyntaxException) OpenIdPrompt(org.forgerock.openidconnect.OpenIdPrompt) URISyntaxException(java.net.URISyntaxException) InvalidClientAuthZHeaderException(org.forgerock.oauth2.core.exceptions.InvalidClientAuthZHeaderException) ParseException(java.text.ParseException) EncodingException(org.owasp.esapi.errors.EncodingException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TemplateException(freemarker.template.TemplateException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) RefreshToken(org.forgerock.oauth2.core.RefreshToken) AMIdentity(com.sun.identity.idm.AMIdentity) 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