Search in sources :

Example 11 with ResourceOwner

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

the class LegacyResponseTypeHandler method handle.

public Map.Entry<String, org.forgerock.oauth2.core.Token> handle(String tokenType, Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws NotFoundException {
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put(TOKEN_TYPE, tokenType);
    data.put(SCOPE, scope);
    data.put(USERNAME, resourceOwner.getId());
    data.put(CLIENT_ID, clientId);
    data.put(REDIRECT_URI, redirectUri);
    data.put(OAuth2Constants.Custom.NONCE, nonce);
    data.put(REALM, realm);
    data.put(OAuth2Constants.Custom.CODE_CHALLENGE, codeChallenge);
    data.put(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD, codeChallengeMethod);
    final HttpServletRequest req = ServletUtils.getRequest(request.<Request>getRequest());
    data.put(OAuth2Constants.Custom.SSO_TOKEN_ID, cookieExtractor.extract(req, ssoCookieName));
    final CoreToken token = responseType.createToken(request.getToken(AccessToken.class), data);
    return new AbstractMap.SimpleEntry<String, org.forgerock.oauth2.core.Token>(responseType.URIParamValue(), new LegacyToken(token));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HashMap(java.util.HashMap) AccessToken(org.forgerock.oauth2.core.AccessToken)

Example 12 with ResourceOwner

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

the class ScopeImpl method evaluateScope.

/**
     * {@inheritDoc}
     */
public Map<String, Object> evaluateScope(CoreToken token) {
    final Map<String, Object> map = new HashMap<String, Object>();
    final Set<String> scopes = token.getScope();
    final String clientId = token.getClientID();
    final String resourceOwner = token.getUserID();
    final String grantType = token.getGrantType();
    AMIdentity id = null;
    try {
        if (clientId != null && OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS.equals(grantType)) {
            id = identityManager.getClientIdentity(clientId, token.getRealm());
        } else if (resourceOwner != null) {
            id = identityManager.getResourceOwnerIdentity(resourceOwner, token.getRealm());
        }
    } catch (UnauthorizedClientException e) {
        logger.error("Unable to get user identity", e);
    }
    if (id == null || scopes.isEmpty()) {
        return map;
    }
    try {
        for (final String scope : scopes) {
            final Set<String> attributes = id.getAttribute(scope);
            if (attributes != null) {
                final Iterator<String> iter = attributes.iterator();
                final StringBuilder builder = new StringBuilder();
                while (iter.hasNext()) {
                    builder.append(iter.next());
                    if (iter.hasNext()) {
                        builder.append(MULTI_ATTRIBUTE_SEPARATOR);
                    }
                }
                map.put(scope, builder.toString());
            }
        }
    } catch (SSOException e) {
        logger.error("Unable to get attribute", e);
    } catch (IdRepoException e) {
        logger.error("Unable to get attribute", e);
    }
    return map;
}
Also used : HashMap(java.util.HashMap) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Example 13 with ResourceOwner

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

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

the class DeviceCodeVerificationResource method verify.

/**
     * Handles POST requests to the OAuth2 device/user endpoint.
     */
@Post
public Representation verify(Representation body) throws ServerException, NotFoundException, InvalidGrantException, OAuth2RestletException {
    final Request restletRequest = getRequest();
    OAuth2Request request = requestFactory.create(restletRequest);
    DeviceCode deviceCode;
    try {
        deviceCode = tokenStore.readDeviceCode(request.<String>getParameter(OAuth2Constants.DeviceCode.USER_CODE), request);
    } catch (InvalidGrantException e) {
        return getTemplateRepresentation(FORM, request, "not_found");
    }
    if (deviceCode == null || deviceCode.isIssued()) {
        return getTemplateRepresentation(FORM, request, "not_found");
    }
    addRequestParamsFromDeviceCode(restletRequest, deviceCode);
    try {
        final String decision = request.getParameter("decision");
        if (StringUtils.isNotEmpty(decision)) {
            final boolean consentGiven = "allow".equalsIgnoreCase(decision);
            final boolean saveConsent = "on".equalsIgnoreCase(request.<String>getParameter("save_consent"));
            if (saveConsent) {
                saveConsent(request);
            }
            if (consentGiven) {
                ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
                deviceCode.setResourceOwnerId(resourceOwner.getId());
                deviceCode.setAuthorized(true);
                tokenStore.updateDeviceCode(deviceCode, request);
            } else {
                tokenStore.deleteDeviceCode(deviceCode.getClientId(), deviceCode.getDeviceCode(), request);
            }
        } else {
            authorizationService.authorize(request);
        }
    } catch (IllegalArgumentException e) {
        if (e.getMessage().contains("client_id")) {
            throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("state"));
        }
        throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"));
    } catch (ResourceOwnerAuthenticationRequired e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), e.getRedirectUri().toString(), null);
    } catch (ResourceOwnerConsentRequired e) {
        return representation.getRepresentation(getContext(), request, "authorize.ftl", getDataModel(e, request));
    } catch (InvalidClientException | 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());
    }
    return getTemplateRepresentation(THANKS_PAGE, request, null);
}
Also used : ResourceOwnerAuthenticationRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired) RedirectUriMismatchException(org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ResourceOwnerConsentRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerConsentRequired) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Request(org.restlet.Request) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) DeviceCode(org.forgerock.oauth2.core.DeviceCode) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Post(org.restlet.resource.Post)

Example 15 with ResourceOwner

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

the class DeviceCodeVerificationResource method saveConsent.

private void saveConsent(OAuth2Request request) throws NotFoundException, ServerException, InvalidScopeException, AccessDeniedException, ResourceOwnerAuthenticationRequired, InteractionRequiredException, BadRequestException, LoginRequiredException, InvalidClientException {
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
    ClientRegistration clientRegistration = clientRegistrationStore.get(request.<String>getParameter(CLIENT_ID), request);
    Set<String> scope = Utils.splitScope(request.<String>getParameter(SCOPE));
    Set<String> validatedScope = providerSettings.validateAuthorizationScope(clientRegistration, scope, request);
    providerSettings.saveConsent(resourceOwner, clientRegistration.getClientId(), validatedScope);
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

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