Search in sources :

Example 6 with ResourceOwner

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

the class CodeResponseType method createToken.

public CoreToken createToken(Token accessToken, Map<String, Object> data) throws NotFoundException {
    final Set<String> scope = (Set<String>) data.get(OAuth2Constants.CoreTokenParams.SCOPE);
    final OAuth2Request request = requestFactory.create(Request.getCurrent());
    final ResourceOwner resourceOwner = ownerAuthenticator.authenticate(request, true);
    final String clientId = (String) data.get(OAuth2Constants.CoreTokenParams.CLIENT_ID);
    final String redirectUri = (String) data.get(OAuth2Constants.CoreTokenParams.REDIRECT_URI);
    final String nonce = (String) data.get(OAuth2Constants.Custom.NONCE);
    final String codeChallenge = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE);
    final String codeChallengeMethod = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD);
    try {
        final Map.Entry<String, Token> tokenEntry = handler.handle(null, scope, resourceOwner, clientId, redirectUri, nonce, request, codeChallenge, codeChallengeMethod);
        return new LegacyAuthorizationTokenAdapter((AuthorizationCode) tokenEntry.getValue());
    } catch (ServerException e) {
        throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(Request.getCurrent(), e.getMessage());
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Set(java.util.Set) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) LegacyAuthorizationTokenAdapter(org.forgerock.openam.oauth2.legacy.LegacyAuthorizationTokenAdapter) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) Token(org.forgerock.oauth2.core.Token) CoreToken(org.forgerock.openam.oauth2.legacy.CoreToken) Map(java.util.Map)

Example 7 with ResourceOwner

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

the class IDTokenResponseType method createToken.

public CoreToken createToken(org.forgerock.oauth2.core.Token accessToken, Map<String, Object> data) throws NotFoundException {
    final OAuth2Request request = requestFactory.create(Request.getCurrent());
    final ResourceOwner resourceOwner = ownerAuthenticator.authenticate(request, true);
    final String clientId = (String) data.get(OAuth2Constants.CoreTokenParams.CLIENT_ID);
    final String nonce = (String) data.get(OAuth2Constants.Custom.NONCE);
    final String codeChallenge = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE);
    final String codeChallengeMethod = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD);
    try {
        final Map.Entry<String, Token> tokenEntry = handler.handle(null, null, resourceOwner, clientId, null, nonce, request, codeChallenge, codeChallengeMethod);
        return new LegacyJwtTokenAdapter((OpenIdConnectToken) tokenEntry.getValue());
    } catch (InvalidClientException e) {
        throw OAuthProblemException.OAuthError.INVALID_CLIENT.handle(Request.getCurrent(), e.getMessage());
    } catch (ServerException e) {
        throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(Request.getCurrent(), e.getMessage());
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) Token(org.forgerock.oauth2.core.Token) CoreToken(org.forgerock.openam.oauth2.legacy.CoreToken) OpenIdConnectToken(org.forgerock.openidconnect.OpenIdConnectToken) Map(java.util.Map) LegacyJwtTokenAdapter(org.forgerock.openam.oauth2.legacy.LegacyJwtTokenAdapter)

Example 8 with ResourceOwner

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

the class OpenAMTokenStoreTest method shouldCreateDeviceCode.

@Test
public void shouldCreateDeviceCode() throws Exception {
    // Given
    OAuth2ProviderSettings providerSettings = mock(OAuth2ProviderSettings.class);
    given(providerSettingsFactory.get(any(OAuth2Request.class))).willReturn(providerSettings);
    given(providerSettings.getDeviceCodeLifetime()).willReturn(10);
    given(tokenStore.query(any(QueryFilter.class))).willReturn(json(array()));
    final RestletOAuth2Request oauth2Request = oAuth2RequestFactory.create(this.request);
    given(request.getAttributes()).willReturn(new ConcurrentHashMap<>(singletonMap("realm", (Object) "MY_REALM")));
    given(realmNormaliser.normalise("MY_REALM")).willReturn("MY_REALM");
    ResourceOwner resourceOwner = mock(ResourceOwner.class);
    given(resourceOwner.getId()).willReturn("RESOURCE_OWNER_ID");
    // When
    DeviceCode code = openAMtokenStore.createDeviceCode(asSet("one", "two"), resourceOwner, "CLIENT ID", "NONCE", "RESPONSE TYPE", "STATE", "ACR VALUES", "PROMPT", "UI LOCALES", "LOGIN HINT", 55, "CLAIMS", oauth2Request, "CODE CHALLENGE", "CODE METHOD");
    // Then
    assertThat(code.getScope()).containsOnly("one", "two");
    assertThat(code.getClientId()).isEqualTo("CLIENT ID");
    assertThat(code.getNonce()).isEqualTo("NONCE");
    assertThat(code.getResponseType()).isEqualTo("RESPONSE TYPE");
    assertThat(code.getState()).isEqualTo("STATE");
    assertThat(code.getAcrValues()).isEqualTo("ACR VALUES");
    assertThat(code.getPrompt()).isEqualTo("PROMPT");
    assertThat(code.getUiLocales()).isEqualTo("UI LOCALES");
    assertThat(code.getLoginHint()).isEqualTo("LOGIN HINT");
    assertThat(code.getClaims()).isEqualTo("CLAIMS");
    assertThat(code.getCodeChallenge()).isEqualTo("CODE CHALLENGE");
    assertThat(code.getCodeChallengeMethod()).isEqualTo("CODE METHOD");
    assertThat(code.getMaxAge()).isEqualTo(55);
    assertThat(code.getTokenName()).isEqualTo("device_code");
    assertThat(code.getExpiryTime()).isCloseTo(System.currentTimeMillis() + 10000, offset(1000L));
    assertThat(code.getTokenId()).matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
    assertThat(code.getUserCode()).matches("[" + OpenAMTokenStore.ALPHABET + "]{8}");
    assertThat(code.getRealm()).isEqualTo("MY_REALM");
}
Also used : RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) DeviceCode(org.forgerock.oauth2.core.DeviceCode) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) Test(org.testng.annotations.Test)

Example 9 with ResourceOwner

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

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

the class OpenIDTokenIssuer method issueToken.

/**
     * Issues an OpenId Connect token, using the details of the access token.
     *
     * @param accessToken The access token requested by the OAuth2 request.
     * @param request The OAuth2 request.
     * @return A {@code Map.Entry} of the token name with the Token instance.
     * @throws ServerException If any internal server error occurs.
     * @throws InvalidClientException If either the request does not contain the client's id or the client fails to be
     *          authenticated.
     * @throws NotFoundException If the realm does not have an OAuth 2.0 provider service.
     */
public Map.Entry<String, String> issueToken(AccessToken accessToken, OAuth2Request request) throws ServerException, InvalidClientException, NotFoundException {
    final Set<String> scope = accessToken.getScope();
    if (scope != null && scope.contains(OAuth2Constants.Params.OPENID)) {
        final ResourceOwner resourceOwner;
        try {
            request.setSession(accessToken.getSessionId());
            resourceOwner = resourceOwnerSessionValidator.validate(request);
            final String nonce = accessToken.getNonce();
            final OpenIdConnectToken openIdToken = tokenStore.createOpenIDToken(resourceOwner, accessToken.getClientId(), accessToken.getClientId(), nonce, getOps(accessToken, request), request);
            final SignedJwt signedJwt = openIdToken.sign();
            return new AbstractMap.SimpleEntry<String, String>(OAuth2Constants.JWTTokenParams.ID_TOKEN, signedJwt.build());
        } catch (SignatureException e) {
            logger.error("Unable to sign JWT", e);
            throw new ServerException("Cant sign JWT");
        } catch (OAuth2Exception e) {
            logger.error("User must be authenticated to issue ID tokens.", e);
            throw new ServerException("User must be authenticated to issue ID tokens.");
        }
    }
    return null;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) SignatureException(java.security.SignatureException) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception)

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)11 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)8 SSOException (com.iplanet.sso.SSOException)7 AMIdentity (com.sun.identity.idm.AMIdentity)7 IdRepoException (com.sun.identity.idm.IdRepoException)6 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)6 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)6 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)6 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)6 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)6 ParseException (java.text.ParseException)4 SMSException (com.sun.identity.sm.SMSException)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 DeviceCode (org.forgerock.oauth2.core.DeviceCode)3 SSOToken (com.iplanet.sso.SSOToken)2 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)2 Set (java.util.Set)2 AccessToken (org.forgerock.oauth2.core.AccessToken)2