Search in sources :

Example 1 with Token

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

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

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

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

the class ClientCredentialsReader method extractCredentials.

/**
     * Extracts the client's credentials from the OAuth2 request.
     *
     * @param request The OAuth2 request.
     * @param endpoint The endpoint this request should be for, or null to disable audience verification.
     * @return The client's credentials.
     * @throws InvalidRequestException If the request contains multiple client credentials.
     * @throws InvalidClientException If the request does not contain the client's id.
     */
public ClientCredentials extractCredentials(OAuth2Request request, String endpoint) throws InvalidRequestException, InvalidClientException, NotFoundException {
    final Request req = request.getRequest();
    boolean basicAuth = false;
    if (req.getChallengeResponse() != null) {
        basicAuth = true;
    }
    final ClientCredentials client;
    Client.TokenEndpointAuthMethod method = CLIENT_SECRET_POST;
    //jwt type first
    if (JWT_PROFILE_CLIENT_ASSERTION_TYPE.equalsIgnoreCase(request.<String>getParameter(CLIENT_ASSERTION_TYPE))) {
        client = verifyJwtBearer(request, basicAuth, endpoint);
        method = PRIVATE_KEY_JWT;
    } else {
        String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
        String clientSecret = request.getParameter(OAuth2Constants.Params.CLIENT_SECRET);
        if (basicAuth && clientId != null) {
            logger.error("Client (" + clientId + ") using multiple authentication methods");
            throw new InvalidRequestException("Client authentication failed");
        }
        if (req.getChallengeResponse() != null) {
            final ChallengeResponse challengeResponse = req.getChallengeResponse();
            clientId = challengeResponse.getIdentifier();
            clientSecret = "";
            if (challengeResponse.getSecret() != null && challengeResponse.getSecret().length > 0) {
                clientSecret = String.valueOf(req.getChallengeResponse().getSecret());
            }
            method = CLIENT_SECRET_BASIC;
        }
        if (clientId == null || clientId.isEmpty()) {
            logger.error("Client Id is not set");
            throw failureFactory.getException(request, "Client authentication failed");
        }
        client = new ClientCredentials(clientId, clientSecret == null ? null : clientSecret.toCharArray(), false, basicAuth);
    }
    final OpenIdConnectClientRegistration cr = clientRegistrationStore.get(client.getClientId(), request);
    final Set<String> scopes = cr.getAllowedScopes();
    //if we're accessing the token endpoint, check we're authenticating using the appropriate method
    if (scopes.contains(OAuth2Constants.Params.OPENID) && req.getResourceRef().getLastSegment().equals(OAuth2Constants.Params.ACCESS_TOKEN) && !cr.getTokenEndpointAuthMethod().equals(method.getType())) {
        throw failureFactory.getException(request, "Invalid authentication method for accessing this endpoint.");
    }
    return client;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) TokenEndpointAuthMethod(org.forgerock.openidconnect.Client.TokenEndpointAuthMethod) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) Client(org.forgerock.openidconnect.Client) ChallengeResponse(org.restlet.data.ChallengeResponse)

Example 5 with Token

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

the class OpenAMOAuth2ProviderSettings method createRSAJWK.

private Map<String, Object> createRSAJWK(RSAPublicKey key, KeyUse use, String alg) throws ServerException {
    String alias = null;
    try {
        alias = getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.KEYSTORE_ALIAS);
    } catch (SSOException | SMSException e) {
        logger.error(e.getMessage());
        throw new ServerException(e);
    }
    if (StringUtils.isBlank(alias)) {
        logger.error("Alias of ID Token Signing Key not set.");
        throw new ServerException("Alias of ID Token Signing Key not set.");
    } else if ("test".equals(alias)) {
        logger.warning("Alias of ID Token Signing Key should be changed from default, 'test'.");
    }
    String kid = Hash.hash(alias + key.getModulus().toString() + key.getPublicExponent().toString());
    return json(object(field("kty", "RSA"), field(OAuth2Constants.JWTTokenParams.KEY_ID, kid), field("use", use.toString()), field("alg", alg), field("n", Base64url.encode(key.getModulus().toByteArray())), field("e", Base64url.encode(key.getPublicExponent().toByteArray())))).asMap();
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) SSOException(com.iplanet.sso.SSOException)

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)33 JsonValue (org.forgerock.json.JsonValue)22 AccessToken (org.forgerock.oauth2.core.AccessToken)18 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)18 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)18 SSOException (com.iplanet.sso.SSOException)16 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)16 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)16 SSOToken (com.iplanet.sso.SSOToken)13 AMIdentity (com.sun.identity.idm.AMIdentity)12 IdRepoException (com.sun.identity.idm.IdRepoException)11 Set (java.util.Set)9 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)9 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)8 Test (org.testng.annotations.Test)8 Map (java.util.Map)6 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)6