Search in sources :

Example 6 with InvalidClientException

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

the class ClaimsParameterValidator method validateRequest.

@Override
public void validateRequest(OAuth2Request request) throws InvalidClientException, InvalidRequestException, RedirectUriMismatchException, UnsupportedResponseTypeException, ServerException, BadRequestException, InvalidScopeException, NotFoundException {
    final OAuth2ProviderSettings settings = providerSettingsFactory.get(request);
    final String claims = request.getParameter(OAuth2Constants.Custom.CLAIMS);
    //if we aren't supporting this no need to validate
    if (!settings.getClaimsParameterSupported()) {
        return;
    }
    //if we support, but it's not requested, no need to validate
    if (claims == null) {
        return;
    }
    final JSONObject claimsJson;
    //convert claims into JSON object
    try {
        claimsJson = new JSONObject(claims);
    } catch (JSONException e) {
        throw new BadRequestException("Invalid JSON in supplied claims parameter.");
    }
    JSONObject userinfoClaims = null;
    try {
        userinfoClaims = claimsJson.getJSONObject(OAuth2Constants.UserinfoEndpoint.USERINFO);
    } catch (Exception e) {
    //fall through
    }
    //results in an Access Token being issued to the Client for use at the UserInfo Endpoint.
    if (userinfoClaims != null) {
        String responseType = request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE);
        if (responseType != null && responseType.trim().equals(OAuth2Constants.JWTTokenParams.ID_TOKEN)) {
            throw new BadRequestException("Must request an access token when providing " + "userinfo in claims parameter.");
        }
    }
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) RedirectUriMismatchException(org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException) JSONException(org.json.JSONException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) UnsupportedResponseTypeException(org.forgerock.oauth2.core.exceptions.UnsupportedResponseTypeException) InvalidScopeException(org.forgerock.oauth2.core.exceptions.InvalidScopeException)

Example 7 with InvalidClientException

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

the class OpenAMScopeValidator method getUserInfo.

/**
     * {@inheritDoc}
     */
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
    Map<String, Object> response = new HashMap<>();
    Bindings scriptVariables = new SimpleBindings();
    SSOToken ssoToken = getUsersSession(request);
    String realm;
    Set<String> scopes;
    AMIdentity id;
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
    try {
        if (token != null) {
            OpenIdConnectClientRegistration clientRegistration;
            try {
                clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
            } catch (InvalidClientException e) {
                logger.message("Unable to retrieve client from store.");
                throw new NotFoundException("No valid client registration found.");
            }
            final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
            //data comes from token when we have one
            realm = token.getRealm();
            scopes = token.getScope();
            id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
            response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
            response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
        } else {
            //otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
            realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
            id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
            String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
            scopes = splitScope(scopeStr);
        }
        scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
        scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
        scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
        scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
        scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
        scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
        ScriptObject script = getOIDCClaimsExtensionScript(realm);
        try {
            return scriptEvaluator.evaluateScript(script, scriptVariables);
        } catch (ScriptException e) {
            logger.message("Error running OIDC claims script", e);
            throw new ServerException("Error running OIDC claims script: " + e.getMessage());
        }
    } catch (ServerException e) {
        //API does not allow ServerExceptions to be thrown!
        throw new NotFoundException(e.getMessage());
    } catch (SSOException e) {
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) SSOException(com.iplanet.sso.SSOException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AMIdentity(com.sun.identity.idm.AMIdentity) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 8 with InvalidClientException

use of org.forgerock.oauth2.core.exceptions.InvalidClientException 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 9 with InvalidClientException

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

the class Saml2GrantTypeHandler method handle.

public AccessToken handle(OAuth2Request request) throws InvalidGrantException, InvalidClientException, InvalidRequestException, ServerException, InvalidScopeException, NotFoundException {
    String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
    Reject.ifTrue(isEmpty(clientId), "Missing parameter, 'client_id'");
    final ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
    Reject.ifTrue(isEmpty(request.<String>getParameter("assertion")), "Missing parameter, 'assertion'");
    final String assertion = request.getParameter(OAuth2Constants.SAML20.ASSERTION);
    logger.trace("Assertion:\n" + assertion);
    final byte[] decodedAssertion = Base64.decode(assertion.replace(" ", "+"));
    if (decodedAssertion == null) {
        logger.error("Decoding assertion failed\nassertion:" + assertion);
    }
    final String finalAssertion = new String(decodedAssertion);
    logger.trace("Decoded assertion:\n" + finalAssertion);
    final Assertion assertionObject;
    final boolean valid;
    try {
        final AssertionFactory factory = AssertionFactory.getInstance();
        assertionObject = factory.createAssertion(finalAssertion);
        valid = validAssertion(assertionObject, getDeploymentUrl(request));
    } catch (SAML2Exception e) {
        logger.error("Error parsing assertion", e);
        throw new InvalidGrantException("Assertion is invalid");
    }
    if (!valid) {
        logger.error("Error parsing assertion");
        throw new InvalidGrantException("Assertion is invalid.");
    }
    logger.trace("Assertion is valid");
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String validatedClaims = providerSettings.validateRequestedClaims((String) request.getParameter(OAuth2Constants.Custom.CLAIMS));
    final String grantType = request.getParameter(OAuth2Constants.Params.GRANT_TYPE);
    final Set<String> scope = splitScope(request.<String>getParameter(OAuth2Constants.Params.SCOPE));
    final Set<String> validatedScope = providerSettings.validateAccessTokenScope(clientRegistration, scope, request);
    logger.trace("Granting scope: " + validatedScope.toString());
    logger.trace("Creating token with data: " + clientRegistration.getAccessTokenType() + "\n" + validatedScope.toString() + "\n" + normaliseRealm(request.<String>getParameter(OAuth2Constants.Params.REALM)) + "\n" + assertionObject.getSubject().getNameID().getValue() + "\n" + clientRegistration.getClientId());
    final AccessToken accessToken = tokenStore.createAccessToken(grantType, BEARER, null, assertionObject.getSubject().getNameID().getValue(), clientRegistration.getClientId(), null, validatedScope, null, null, validatedClaims, request);
    logger.trace("Token created: " + accessToken.toString());
    providerSettings.additionalDataToReturnFromTokenEndpoint(accessToken, request);
    if (validatedScope != null && !validatedScope.isEmpty()) {
        accessToken.put(SCOPE, joinScope(validatedScope));
    }
    tokenStore.updateAccessToken(accessToken);
    return accessToken;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AssertionFactory(com.sun.identity.saml2.assertion.AssertionFactory) ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) AccessToken(org.forgerock.oauth2.core.AccessToken) Assertion(com.sun.identity.saml2.assertion.Assertion) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 10 with InvalidClientException

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

the class ClientAuthenticatorImpl method authenticate.

/**
     * {@inheritDoc}
     */
public ClientRegistration authenticate(OAuth2Request request, String endpoint) throws InvalidClientException, InvalidRequestException, NotFoundException {
    final ClientCredentials clientCredentials = clientCredentialsReader.extractCredentials(request, endpoint);
    Reject.ifTrue(isEmpty(clientCredentials.getClientId()), "Missing parameter, 'client_id'");
    final String realm = realmNormaliser.normalise(request.<String>getParameter(OAuth2Constants.Custom.REALM));
    boolean authenticated = false;
    try {
        final ClientRegistration clientRegistration = clientRegistrationStore.get(clientCredentials.getClientId(), request);
        // Do not need to authenticate public clients
        if (!clientRegistration.isConfidential()) {
            return clientRegistration;
        }
        if (!clientCredentials.isAuthenticated() && !authenticate(request, clientCredentials.getClientId(), clientCredentials.getClientSecret(), realm)) {
            logger.error("ClientVerifierImpl::Unable to verify password for: " + clientCredentials.getClientId());
            throw failureFactory.getException(request, "Client authentication failed");
        }
        authenticated = true;
        return clientRegistration;
    } finally {
        if (auditLogger.isAuditLogEnabled()) {
            if (authenticated) {
                String[] obs = { clientCredentials.getClientId() };
                auditLogger.logAccessMessage("AUTHENTICATED_CLIENT", obs, null);
            } else {
                String[] obs = { clientCredentials.getClientId() };
                auditLogger.logErrorMessage("FAILED_AUTHENTICATE_CLIENT", obs, null);
            }
        }
    }
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration)

Aggregations

OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)14 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)13 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)12 ClientRegistration (org.forgerock.oauth2.core.ClientRegistration)11 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)8 Test (org.testng.annotations.Test)6 HashSet (java.util.HashSet)5 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)5 OAuth2Exception (org.forgerock.oauth2.core.exceptions.OAuth2Exception)5 BeforeTest (org.testng.annotations.BeforeTest)5 JsonValue (org.forgerock.json.JsonValue)4 SignedJwt (org.forgerock.json.jose.jws.SignedJwt)4 RedirectUriMismatchException (org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException)4 JSONObject (org.json.JSONObject)4 Request (org.restlet.Request)4 BeforeMethod (org.testng.annotations.BeforeMethod)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 AccessToken (org.forgerock.oauth2.core.AccessToken)3 ClientRegistrationStore (org.forgerock.oauth2.core.ClientRegistrationStore)3