Search in sources :

Example 1 with AccessToken

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

the class ResourceSetRegistrationEndpointTest method setup.

@BeforeMethod
@SuppressWarnings("unchecked")
public void setup() throws ServerException, InvalidGrantException, NotFoundException {
    store = mock(ResourceSetStore.class);
    validator = mock(ResourceSetDescriptionValidator.class);
    OAuth2RequestFactory<?, Request> requestFactory = mock(OAuth2RequestFactory.class);
    Set<ResourceSetRegistrationHook> hooks = new HashSet<>();
    hook = mock(ResourceSetRegistrationHook.class);
    hooks.add(hook);
    labelRegistration = mock(ResourceSetLabelRegistration.class);
    ExtensionFilterManager extensionFilterManager = mock(ExtensionFilterManager.class);
    resourceRegistrationFilter = mock(ResourceRegistrationFilter.class);
    given(extensionFilterManager.getFilters(ResourceRegistrationFilter.class)).willReturn(Collections.singletonList(resourceRegistrationFilter));
    OAuth2ProviderSettingsFactory providerSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
    OAuth2ProviderSettings providerSettings = mock(OAuth2ProviderSettings.class);
    given(providerSettingsFactory.get(Matchers.<OAuth2Request>anyObject())).willReturn(providerSettings);
    given(providerSettings.getResourceSetStore()).willReturn(store);
    ExceptionHandler exceptionHandler = mock(ExceptionHandler.class);
    UmaLabelsStore umaLabelsStore = mock(UmaLabelsStore.class);
    endpoint = spy(new ResourceSetRegistrationEndpoint(providerSettingsFactory, validator, requestFactory, hooks, labelRegistration, extensionFilterManager, exceptionHandler, umaLabelsStore, jacksonRepresentationFactory));
    Request request = mock(Request.class);
    ChallengeResponse challengeResponse = new ChallengeResponse(ChallengeScheme.HTTP_BASIC);
    challengeResponse.setRawValue("PAT");
    given(request.getChallengeResponse()).willReturn(challengeResponse);
    given(endpoint.getRequest()).willReturn(request);
    AccessToken accessToken = mock(AccessToken.class);
    given(accessToken.getClientId()).willReturn("CLIENT_ID");
    given(accessToken.getResourceOwnerId()).willReturn("RESOURCE_OWNER_ID");
    response = mock(Response.class);
    given(endpoint.getResponse()).willReturn(response);
    OAuth2Request oAuth2Request = mock(OAuth2Request.class);
    given(requestFactory.create(Matchers.<Request>anyObject())).willReturn(oAuth2Request);
    given(oAuth2Request.getToken(AccessToken.class)).willReturn(accessToken);
}
Also used : ResourceSetRegistrationHook(org.forgerock.oauth2.restlet.resources.ResourceSetRegistrationHook) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Request(org.restlet.Request) ResourceRegistrationFilter(org.forgerock.openam.oauth2.extensions.ResourceRegistrationFilter) ResourceSetDescriptionValidator(org.forgerock.oauth2.restlet.resources.ResourceSetDescriptionValidator) ChallengeResponse(org.restlet.data.ChallengeResponse) ExceptionHandler(org.forgerock.oauth2.restlet.ExceptionHandler) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2ProviderSettingsFactory(org.forgerock.oauth2.core.OAuth2ProviderSettingsFactory) ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) AccessToken(org.forgerock.oauth2.core.AccessToken) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) UmaLabelsStore(org.forgerock.openam.oauth2.resources.labels.UmaLabelsStore) ExtensionFilterManager(org.forgerock.openam.oauth2.extensions.ExtensionFilterManager) HashSet(java.util.HashSet) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 2 with AccessToken

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

the class OpenAMTokenStoreTest method shouldNotReadOtherRealmsAccessToken.

@Test(expectedExceptions = InvalidGrantException.class)
public void shouldNotReadOtherRealmsAccessToken() throws Exception {
    //Given
    JsonValue token = json(object(field("tokenName", Collections.singleton("access_token")), field("realm", Collections.singleton("/otherrealm"))));
    given(tokenStore.read("TOKEN_ID")).willReturn(token);
    given(realmNormaliser.normalise("/otherrealm")).willReturn("/otherrealm");
    ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
    given(request.getAttributes()).willReturn(attributes);
    attributes.put("realm", "/testrealm");
    OAuth2Request request = oAuth2RequestFactory.create(this.request);
    //When
    AccessToken accessToken = openAMtokenStore.readAccessToken(request, "TOKEN_ID");
//Then
// expect InvalidGrantException
}
Also used : RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AccessToken(org.forgerock.oauth2.core.AccessToken) JsonValue(org.forgerock.json.JsonValue) BDDMockito.anyString(org.mockito.BDDMockito.anyString) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test)

Example 3 with AccessToken

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

the class OpenAMTokenStoreTest method realmAgnosticTokenStoreShouldIgnoreRealmMismatch.

@Test
public void realmAgnosticTokenStoreShouldIgnoreRealmMismatch() throws Exception {
    //Given
    OpenAMTokenStore realmAgnosticTokenStore = new OAuth2GuiceModule.RealmAgnosticTokenStore(tokenStore, providerSettingsFactory, oAuth2UrisFactory, clientRegistrationStore, realmNormaliser, ssoTokenManager, cookieExtractor, auditLogger, debug, new SecureRandom(), failureFactory);
    JsonValue token = json(object(field("tokenName", Collections.singleton("access_token")), field("realm", Collections.singleton("/otherrealm"))));
    given(tokenStore.read("TOKEN_ID")).willReturn(token);
    ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
    given(request.getAttributes()).willReturn(attributes);
    attributes.put("realm", "/testrealm");
    OAuth2Request request = oAuth2RequestFactory.create(this.request);
    //When
    AccessToken accessToken = realmAgnosticTokenStore.readAccessToken(request, "TOKEN_ID");
    //Then
    assertThat(accessToken).isNotNull();
    assertThat(request.getToken(AccessToken.class)).isSameAs(accessToken);
}
Also used : RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AccessToken(org.forgerock.oauth2.core.AccessToken) JsonValue(org.forgerock.json.JsonValue) SecureRandom(java.security.SecureRandom) BDDMockito.anyString(org.mockito.BDDMockito.anyString) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test)

Example 4 with AccessToken

use of org.forgerock.oauth2.core.AccessToken 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 5 with AccessToken

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

the class ConnectClientRegistration method createClient.

/**
     * Handles POST requests to the OpenId Connect client registration endpoint for creating OpenId Connect client
     * registrations.
     *
     * @param entity The representation of the client registration details.
     * @return The representation of the client registration details as created in the store.
     * @throws OAuth2RestletException If an error occurs whilst processing the client registration.
     */
@Post
public Representation createClient(Representation entity) throws OAuth2RestletException {
    final OAuth2Request request = requestFactory.create(getRequest());
    final ChallengeResponse authHeader = getRequest().getChallengeResponse();
    final String accessToken = authHeader != null ? authHeader.getRawValue() : null;
    try {
        final String deploymentUrl = getRequest().getHostRef().toString() + "/" + getRequest().getResourceRef().getSegments().get(0);
        final JsonValue registration = clientRegistrationService.createRegistration(accessToken, deploymentUrl, request);
        setStatus(Status.SUCCESS_CREATED);
        return jacksonRepresentationFactory.create(registration.asMap());
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2RestletException(org.forgerock.oauth2.restlet.OAuth2RestletException) JsonValue(org.forgerock.json.JsonValue) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) ChallengeResponse(org.restlet.data.ChallengeResponse) Post(org.restlet.resource.Post)

Aggregations

AccessToken (org.forgerock.oauth2.core.AccessToken)37 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)22 Test (org.testng.annotations.Test)17 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)14 JsonValue (org.forgerock.json.JsonValue)13 Request (org.restlet.Request)12 ChallengeResponse (org.restlet.data.ChallengeResponse)10 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)9 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)7 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)6 Response (org.restlet.Response)6 Map (java.util.Map)5 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)5 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)5 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)5 BeforeMethod (org.testng.annotations.BeforeMethod)5 HashMap (java.util.HashMap)4 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)4 InvalidTokenException (org.forgerock.oauth2.core.exceptions.InvalidTokenException)4 JSONObject (org.json.JSONObject)4