Search in sources :

Example 26 with InvalidClientException

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

the class AuthorizeResource method authorize.

/**
     * Handles POST requests to the OAuth2 authorize endpoint.
     * <br/>
     * This method will be called when a user has given their consent for an authorization request.
     *
     * @param entity The entity on the request.
     * @return The body to be sent in the response to the user agent.
     * @throws OAuth2RestletException If a OAuth2 error occurs whilst processing the authorization request.
     */
@Post
public Representation authorize(Representation entity) throws OAuth2RestletException {
    final OAuth2Request request = requestFactory.create(getRequest());
    for (AuthorizeRequestHook hook : hooks) {
        hook.beforeAuthorizeHandling(request, getRequest(), getResponse());
    }
    final boolean consentGiven = "allow".equalsIgnoreCase(request.<String>getParameter("decision"));
    final boolean saveConsent = "on".equalsIgnoreCase(request.<String>getParameter("save_consent"));
    try {
        final AuthorizationToken authorizationToken = authorizationService.authorize(request, consentGiven, saveConsent);
        final String redirectUri = request.getParameter("redirect_uri");
        Representation response = representation.toRepresentation(getContext(), getRequest(), getResponse(), authorizationToken, redirectUri);
        for (AuthorizeRequestHook hook : hooks) {
            hook.afterAuthorizeSuccess(request, getRequest(), getResponse());
        }
        return response;
    } catch (ResourceOwnerAuthenticationRequired e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), e.getRedirectUri().toString(), null);
    } catch (InvalidClientException e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("state"));
    } catch (RedirectUriMismatchException e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("state"));
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"), e.getParameterLocation());
    }
}
Also used : ResourceOwnerAuthenticationRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AuthorizationToken(org.forgerock.oauth2.core.AuthorizationToken) RedirectUriMismatchException(org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) Representation(org.restlet.representation.Representation) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Post(org.restlet.resource.Post)

Example 27 with InvalidClientException

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

the class EndSessionTest method setup.

@BeforeMethod
public void setup() throws InvalidClientException, SignatureException, NotFoundException {
    idToken = "eyAidHlwIjogIkpXVCIsICJhbGciOiAiSFMyNTYiIH0.eyAidG9rZW5OYW1lIjogImlkX3Rva2VuIiwgImF6cCI6ICJOZXdPcG" + "VuSWRDbGllbnQiLCAic3ViIjogIlRlc3RVc2VyIiwgImF0X2hhc2giOiAibHhSNE1BcGV1aXl0dWxiVFI4OV9wQSIsICJpc3MiOi" + "AiaHR0cDovL29wZW5hbS5leGFtcGxlLmNvbTo4MDgwL29wZW5hbS9vYXV0aDIiLCAib3JnLmZvcmdlcm9jay5vcGVuaWRjb25uZW" + "N0Lm9wcyI6ICI2OTYzOTc4MC04NjkzLTQ1ODktOTk1Ni05ZThkM2UxZWI2YjQiLCAiaWF0IjogMTQzNjM1MjM4MiwgImF1dGhfdG" + "ltZSI6IDE0MzYzNTIzODIsICJleHAiOiAxNDM2MzUyOTgyLCAidG9rZW5UeXBlIjogIkpXVFRva2VuIiwgIm5vbmNlIjogIjEyMz" + "Q1IiwgInJlYWxtIjogIi8iLCAiYXVkIjogWyAiTmV3T3BlbklkQ2xpZW50IiBdLCAiY19oYXNoIjogIkY3RENrMkE5cDVmeUN0VF" + "hpYmF5V2ciIH0.0uIyHGAsr04gu9H4cJ57UPYVJmSJwjCakozPATlCcuE";
    oAuth2Request = mock(OAuth2Request.class);
    when(oAuth2Request.getParameter(OAuth2Constants.Params.END_SESSION_ID_TOKEN_HINT)).thenReturn(idToken);
    OAuth2RequestFactory<?, Request> requestFactory = mock(OAuth2RequestFactory.class);
    ExceptionHandler exceptionHandler = mock(ExceptionHandler.class);
    ClientRegistrationStore clientRegistrationStore = mock(ClientRegistrationStore.class);
    openIDConnectEndSession = mock(OpenIDConnectEndSession.class);
    endSession = new EndSession(requestFactory, openIDConnectEndSession, exceptionHandler, clientRegistrationStore);
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    when(response.getEntity()).thenReturn(mock(Representation.class));
    endSession.setRequest(request);
    endSession.setResponse(response);
    when(requestFactory.create(any(Request.class))).thenReturn(oAuth2Request);
    client = mock(ClientRegistration.class);
    when(clientRegistrationStore.get(anyString(), any(OAuth2Request.class))).thenReturn(client);
}
Also used : ExceptionHandler(org.forgerock.oauth2.restlet.ExceptionHandler) Response(org.restlet.Response) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OpenIDConnectEndSession(org.forgerock.openidconnect.OpenIDConnectEndSession) OpenIDConnectEndSession(org.forgerock.openidconnect.OpenIDConnectEndSession) Representation(org.restlet.representation.Representation) ClientRegistrationStore(org.forgerock.oauth2.core.ClientRegistrationStore) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 28 with InvalidClientException

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

the class OAuth2UserApplications method deleteInstance.

/**
     * Allows users to revoke an OAuth2 application. This will remove their consent and revoke any access and refresh
     * tokens with a matching client id.
     * @param context The request context.
     * @param resourceId The id of the OAuth2 client.
     * @return A promise of the removed application.
     */
@Delete
public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId) {
    String userId = contextHelper.getUserId(context);
    String realm = contextHelper.getRealm(context);
    debug.message("Revoking access to OAuth2 client {} for user {}", resourceId, userId);
    try {
        oAuth2ProviderSettingsFactory.get(context).revokeConsent(userId, resourceId);
        QueryFilter<CoreTokenField> queryFilter = and(getQueryFilter(userId, realm), equalTo(CLIENT_ID.getField(), resourceId));
        JsonValue tokens = tokenStore.query(queryFilter);
        if (tokens.asCollection().isEmpty()) {
            return new org.forgerock.json.resource.NotFoundException().asPromise();
        }
        for (JsonValue token : tokens) {
            String tokenId = getAttributeValue(token, ID.getOAuthField());
            debug.message("Removing OAuth2 token {} with client {} for user {}", tokenId, resourceId, userId);
            tokenStore.delete(tokenId);
        }
        return getResourceResponse(context, resourceId, tokens).asPromise();
    } catch (CoreTokenException | InvalidClientException | NotFoundException | ServerException e) {
        debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
        return new InternalServerErrorException(e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
        return e.asPromise();
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Delete(org.forgerock.json.resource.annotations.Delete)

Example 29 with InvalidClientException

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

the class OAuth2UserApplications method getResourceResponse.

private ResourceResponse getResourceResponse(Context context, String clientId, Iterable<JsonValue> tokens) throws NotFoundException, InvalidClientException, ServerException, InternalServerErrorException {
    String realm = getAttributeValue(tokens.iterator().next(), REALM.getOAuthField());
    OAuth2ProviderSettings oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(context);
    ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, realm, context);
    Map<String, String> scopeDescriptions = clientRegistration.getScopeDescriptions(getLocale(context));
    Map<String, String> scopes = new HashMap<>();
    for (JsonValue token : tokens) {
        for (String scope : token.get(SCOPE.getOAuthField()).asSet(String.class)) {
            if (scopeDescriptions.containsKey(scope)) {
                scopes.put(scope, scopeDescriptions.get(scope));
            } else {
                scopes.put(scope, scope);
            }
        }
    }
    String displayName = clientRegistration.getDisplayName(getLocale(context));
    String expiryDateTime = calculateExpiryDateTime(tokens, oAuth2ProviderSettings);
    JsonValue content = json(object(field("_id", clientId), field("name", displayName), field("scopes", scopes), field("expiryDateTime", expiryDateTime)));
    return Responses.newResourceResponse(clientId, String.valueOf(content.getObject().hashCode()), content);
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 30 with InvalidClientException

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

the class CheckSessionImpl method getClientSessionURI.

/**
     * {@inheritDoc}
     */
public String getClientSessionURI(HttpServletRequest request) throws UnauthorizedClientException, InvalidClientException, NotFoundException {
    SignedJwt jwt = getIDToken(request);
    if (jwt == null) {
        return "";
    }
    final ClientRegistration clientRegistration = getClientRegistration(jwt);
    if (clientRegistration != null && !isJwtValid(jwt, clientRegistration)) {
        return "";
    }
    return clientRegistration.getClientSessionURI();
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) SignedJwt(org.forgerock.json.jose.jws.SignedJwt)

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