Search in sources :

Example 6 with OAuth2Uris

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

the class UmaUrisFactory method get.

/**
     * <p>Gets the instance of the UmaProviderSettings.</p>
     *
     * <p>Cache each provider settings on the realm it was created for.</p>
     *
     * @param context The context instance from which the base URL can be deduced.
     * @param realmInfo The realm.
     * @return The OAuth2ProviderSettings instance.
     */
public UmaUris get(Context context, RealmInfo realmInfo) throws NotFoundException, ServerException {
    String absoluteRealm = realmInfo.getAbsoluteRealm();
    HttpContext httpContext = context.asContext(HttpContext.class);
    String baseUrl;
    try {
        baseUrl = baseURLProviderFactory.get(absoluteRealm).getRealmURL(httpContext, "/uma", absoluteRealm);
    } catch (InvalidBaseUrlException e) {
        throw new ServerException("Configuration error");
    }
    UmaUris uris = urisMap.get(baseUrl);
    if (uris == null) {
        OAuth2Uris oAuth2Uris = oAuth2UriFactory.get(context, realmInfo);
        uris = get(absoluteRealm, oAuth2Uris, baseUrl);
    }
    return uris;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) HttpContext(org.forgerock.json.resource.http.HttpContext) InvalidBaseUrlException(org.forgerock.openam.services.baseurl.InvalidBaseUrlException)

Example 7 with OAuth2Uris

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

the class AuthorizationRequestEndpointTest method setup.

@BeforeMethod
@SuppressWarnings("unchecked")
public void setup() throws ServerException, InvalidGrantException, NotFoundException, EntitlementException, JSONException {
    requestFactory = mock(OAuth2RequestFactory.class);
    OAuth2Request oAuth2Request = mock(OAuth2Request.class);
    given(requestFactory.create(any(Request.class))).willReturn(oAuth2Request);
    given(oAuth2Request.getParameter("realm")).willReturn("REALM");
    accessToken = mock(AccessToken.class);
    oauth2TokenStore = mock(TokenStore.class);
    given(oauth2TokenStore.readAccessToken(Matchers.<OAuth2Request>anyObject(), anyString())).willReturn(accessToken);
    given(accessToken.getClientId()).willReturn(RS_CLIENT_ID);
    given(accessToken.getResourceOwnerId()).willReturn(REQUESTING_PARTY_ID);
    umaAuditLogger = mock(UmaAuditLogger.class);
    umaTokenStore = mock(UmaTokenStore.class);
    rpt = mock(RequestingPartyToken.class);
    given(rpt.getId()).willReturn("1");
    permissionTicket = mock(PermissionTicket.class);
    given(permissionTicket.getExpiryTime()).willReturn(System.currentTimeMillis() + 10000);
    given(permissionTicket.getResourceSetId()).willReturn(RS_ID);
    given(permissionTicket.getResourceServerClientId()).willReturn(RS_CLIENT_ID);
    given(permissionTicket.getRealm()).willReturn("REALM");
    given(umaTokenStore.readPermissionTicket(anyString())).willReturn(permissionTicket);
    given(umaTokenStore.createRPT(Matchers.<PermissionTicket>anyObject())).willReturn(rpt);
    resourceSetStore = mock(ResourceSetStore.class);
    ResourceSetDescription resourceSet = new ResourceSetDescription();
    resourceSet.setId(RS_DESCRIPTION_ID);
    resourceSet.setResourceOwnerId(RESOURCE_OWNER_ID);
    given(resourceSetStore.query(QueryFilter.equalTo(ResourceSetTokenField.RESOURCE_SET_ID, RS_ID))).willReturn(Collections.singleton(resourceSet));
    umaProviderSettings = mock(UmaProviderSettings.class);
    policyEvaluator = mock(Evaluator.class);
    given(umaProviderSettings.getPolicyEvaluator(any(Subject.class), eq(RS_CLIENT_ID.toLowerCase()))).willReturn(policyEvaluator);
    given(umaProviderSettings.getUmaTokenStore()).willReturn(umaTokenStore);
    umaProviderSettingsFactory = mock(UmaProviderSettingsFactory.class);
    given(umaProviderSettingsFactory.get(Matchers.<Request>anyObject())).willReturn(umaProviderSettings);
    given(umaProviderSettings.getUmaTokenStore()).willReturn(umaTokenStore);
    OAuth2ProviderSettingsFactory oauth2ProviderSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
    OAuth2ProviderSettings oauth2ProviderSettings = mock(OAuth2ProviderSettings.class);
    given(oauth2ProviderSettingsFactory.get(any(OAuth2Request.class))).willReturn(oauth2ProviderSettings);
    given(oauth2ProviderSettings.getResourceSetStore()).willReturn(resourceSetStore);
    OAuth2UrisFactory<RealmInfo> oauth2UrisFactory = mock(OAuth2UrisFactory.class);
    OAuth2Uris oauth2Uris = mock(OAuth2Uris.class);
    given(oauth2UrisFactory.get(any(OAuth2Request.class))).willReturn(oauth2Uris);
    given(oauth2Uris.getIssuer()).willReturn("ISSUER");
    pendingRequestsService = mock(PendingRequestsService.class);
    Map<String, ClaimGatherer> claimGatherers = new HashMap<>();
    idTokenClaimGatherer = mock(IdTokenClaimGatherer.class);
    claimGatherers.put(IdTokenClaimGatherer.FORMAT, idTokenClaimGatherer);
    ExtensionFilterManager extensionFilterManager = mock(ExtensionFilterManager.class);
    requestAuthorizationFilter = mock(RequestAuthorizationFilter.class);
    given(extensionFilterManager.getFilters(RequestAuthorizationFilter.class)).willReturn(Collections.singletonList(requestAuthorizationFilter));
    UmaExceptionHandler exceptionHandler = mock(UmaExceptionHandler.class);
    endpoint = spy(new AuthorizationRequestEndpoint2(umaProviderSettingsFactory, oauth2TokenStore, requestFactory, oauth2ProviderSettingsFactory, oauth2UrisFactory, umaAuditLogger, pendingRequestsService, claimGatherers, extensionFilterManager, exceptionHandler, jacksonRepresentationFactory));
    request = mock(Request.class);
    given(endpoint.getRequest()).willReturn(request);
    response = mock(Response.class);
    endpoint.setResponse(response);
    requestBody = mock(JSONObject.class);
    given(requestBody.toString()).willReturn("{\"ticket\": \"016f84e8-f9b9-11e0-bd6f-0021cc6004de\"}");
    entity = mock(JsonRepresentation.class);
    given(entity.getJsonObject()).willReturn(requestBody);
}
Also used : OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) RealmInfo(org.forgerock.openam.core.RealmInfo) OAuth2RequestFactory(org.forgerock.oauth2.core.OAuth2RequestFactory) OAuth2ProviderSettingsFactory(org.forgerock.oauth2.core.OAuth2ProviderSettingsFactory) AccessToken(org.forgerock.oauth2.core.AccessToken) ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) UmaAuditLogger(org.forgerock.openam.uma.audit.UmaAuditLogger) UmaPendingRequest(org.forgerock.openam.sm.datalayer.impl.uma.UmaPendingRequest) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.restlet.Request) RequestAuthorizationFilter(org.forgerock.openam.uma.extensions.RequestAuthorizationFilter) Evaluator(com.sun.identity.entitlement.Evaluator) Subject(javax.security.auth.Subject) Response(org.restlet.Response) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) JSONObject(org.json.JSONObject) TokenStore(org.forgerock.oauth2.core.TokenStore) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) ExtensionFilterManager(org.forgerock.openam.oauth2.extensions.ExtensionFilterManager) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 8 with OAuth2Uris

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

the class OpenAMTokenStore method createOpenIDToken.

/**
     * {@inheritDoc}
     */
public OpenIdConnectToken createOpenIDToken(ResourceOwner resourceOwner, String clientId, String authorizationParty, String nonce, String ops, OAuth2Request request) throws ServerException, InvalidClientException, NotFoundException {
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    OAuth2Uris oAuth2Uris = oauth2UrisFactory.get(request);
    final OpenIdConnectClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
    final String algorithm = clientRegistration.getIDTokenSignedResponseAlgorithm();
    final long currentTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    final long exp = TimeUnit.MILLISECONDS.toSeconds(clientRegistration.getJwtTokenLifeTime(providerSettings)) + currentTimeInSeconds;
    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    final String iss = oAuth2Uris.getIssuer();
    final List<String> amr = getAMRFromAuthModules(request, providerSettings);
    final byte[] clientSecret = clientRegistration.getClientSecret().getBytes(Utils.CHARSET);
    final KeyPair keyPair = providerSettings.getServerKeyPair();
    final String atHash = generateAtHash(algorithm, request, providerSettings);
    final String cHash = generateCHash(algorithm, request, providerSettings);
    final String acr = getAuthenticationContextClassReference(request);
    final String kid = generateKid(providerSettings.getJWKSet(), algorithm);
    final String opsId = UUID.randomUUID().toString();
    final long authTime = resourceOwner.getAuthTime();
    final String subId = clientRegistration.getSubValue(resourceOwner.getId(), providerSettings);
    try {
        tokenStore.create(json(object(field(OAuth2Constants.CoreTokenParams.ID, set(opsId)), field(OAuth2Constants.JWTTokenParams.LEGACY_OPS, set(ops)), field(OAuth2Constants.CoreTokenParams.EXPIRE_TIME, set(Long.toString(TimeUnit.SECONDS.toMillis(exp)))))));
    } catch (CoreTokenException e) {
        logger.error("Unable to create id_token user session token", e);
        throw new ServerException("Could not create token in CTS");
    }
    final OpenAMOpenIdConnectToken oidcToken = new OpenAMOpenIdConnectToken(kid, clientSecret, keyPair, algorithm, iss, subId, clientId, authorizationParty, exp, currentTimeInSeconds, authTime, nonce, opsId, atHash, cHash, acr, amr, realm);
    request.setSession(ops);
    //See spec section 5.4. - add claims to id_token based on 'response_type' parameter
    String responseType = request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE);
    if (providerSettings.isAlwaysAddClaimsToToken() || (responseType != null && responseType.trim().equals(OAuth2Constants.JWTTokenParams.ID_TOKEN))) {
        appendIdTokenClaims(request, providerSettings, oidcToken);
    } else if (providerSettings.getClaimsParameterSupported()) {
        appendRequestedIdTokenClaims(request, providerSettings, oidcToken);
    }
    return oidcToken;
}
Also used : OpenAMOpenIdConnectToken(org.forgerock.openam.openidconnect.OpenAMOpenIdConnectToken) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) KeyPair(java.security.KeyPair) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 9 with OAuth2Uris

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

the class DeviceCodeGrantTypeHandlerTest method setup.

@BeforeMethod
public void setup() throws Exception {
    initMocks(this);
    OAuth2ProviderSettingsFactory providerSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
    when(providerSettingsFactory.get(request)).thenReturn(providerSettings);
    when(providerSettings.getDeviceCodePollInterval()).thenReturn(5);
    when(providerSettings.validateRequestedClaims(anyString())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return (String) invocation.getArguments()[0];
        }
    });
    OAuth2UrisFactory oAuth2UrisFactory = mock(OAuth2UrisFactory.class);
    when(oAuth2UrisFactory.get(request)).thenReturn(oAuth2Uris);
    ClientAuthenticator clientAuthenticator = mock(ClientAuthenticator.class);
    ClientRegistration clientRegistration = mock(ClientRegistration.class);
    when(clientAuthenticator.authenticate(eq(request), anyString())).thenReturn(clientRegistration);
    accessTokenGenerator = new GrantTypeAccessTokenGenerator(tokenStore);
    when(tokenStore.createAccessToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(RefreshToken.class), anyString(), anyString(), any(OAuth2Request.class))).thenReturn(accessToken);
    when(tokenStore.createRefreshToken(anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(OAuth2Request.class), anyString())).thenReturn(refreshToken);
    ClientAuthenticationFailureFactory failureFactory = mock(ClientAuthenticationFailureFactory.class);
    InvalidClientException expectedResult = mock(InvalidClientException.class);
    when(expectedResult.getError()).thenReturn("invalid_client");
    when(failureFactory.getException()).thenReturn(expectedResult);
    when(failureFactory.getException(anyString())).thenReturn(expectedResult);
    when(failureFactory.getException(any(OAuth2Request.class), anyString())).thenReturn(expectedResult);
    grantTypeHandler = new DeviceCodeGrantTypeHandler(providerSettingsFactory, clientAuthenticator, tokenStore, clientRegistrationStore, failureFactory, oAuth2UrisFactory, accessTokenGenerator);
}
Also used : ClientAuthenticationFailureFactory(org.forgerock.oauth2.core.exceptions.ClientAuthenticationFailureFactory) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 10 with OAuth2Uris

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

the class OpenAMOAuth2UrisFactory method getOAuth2Uris.

private synchronized OAuth2Uris getOAuth2Uris(String absoluteRealm, String baseUrlPattern) throws NotFoundException {
    OAuth2Uris uris = urisMap.get(baseUrlPattern);
    if (uris != null) {
        return uris;
    }
    OAuth2ProviderSettings oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(absoluteRealm);
    uris = new OAuth2UrisImpl(baseUrlPattern, absoluteRealm, oAuth2ProviderSettings);
    urisMap.put(baseUrlPattern, uris);
    return uris;
}
Also used : OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Aggregations

OAuth2Uris (org.forgerock.oauth2.core.OAuth2Uris)9 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)6 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)6 InvalidBaseUrlException (org.forgerock.openam.services.baseurl.InvalidBaseUrlException)4 BeforeMethod (org.testng.annotations.BeforeMethod)3 KeyPair (java.security.KeyPair)2 HashMap (java.util.HashMap)2 JsonValue (org.forgerock.json.JsonValue)2 OAuth2ProviderSettingsFactory (org.forgerock.oauth2.core.OAuth2ProviderSettingsFactory)2 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)2 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)2 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)2 RealmInfo (org.forgerock.openam.core.RealmInfo)2 BaseURLProvider (org.forgerock.openam.services.baseurl.BaseURLProvider)2 UmaPendingRequest (org.forgerock.openam.sm.datalayer.impl.uma.UmaPendingRequest)2 Request (org.restlet.Request)2 Evaluator (com.sun.identity.entitlement.Evaluator)1 AMIdentity (com.sun.identity.idm.AMIdentity)1 Subject (javax.security.auth.Subject)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1