Search in sources :

Example 1 with ResourceOwner

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

the class OpenAMOAuth2ProviderSettings method isConsentSaved.

/**
     * {@inheritDoc}
     */
public boolean isConsentSaved(ResourceOwner resourceOwner, String clientId, Set<String> scope) {
    String consentAttribute = null;
    try {
        consentAttribute = getStringSetting(realm, OAuth2ProviderService.SAVED_CONSENT_ATTRIBUTE);
        if (consentAttribute != null) {
            AMIdentity id = ((OpenAMResourceOwner) resourceOwner).getIdentity();
            if (id != null) {
                Set<String> attributeSet = id.getAttribute(consentAttribute);
                if (attributeSet != null) {
                    if (logger.messageEnabled()) {
                        logger.message("Existing saved consent value for resourceOwner: " + resourceOwner.getId() + " in attribute:" + consentAttribute + " in realm:" + realm + " is:" + attributeSet);
                    }
                    //attribute set is in the form of client_id|scope1 scope2 scope3
                    for (String consent : attributeSet) {
                        int loc = consent.indexOf(" ");
                        String consentClientId = consent.substring(0, loc);
                        String[] scopesArray = null;
                        if (loc + 1 < consent.length()) {
                            scopesArray = consent.substring(loc + 1, consent.length()).split(" ");
                        }
                        Set<String> consentScopes;
                        if (scopesArray != null && scopesArray.length > 0) {
                            consentScopes = new HashSet<String>(Arrays.asList(scopesArray));
                        } else {
                            consentScopes = new HashSet<String>();
                        }
                        //if both the client and the scopes are identical to the saved consent then approve
                        if (clientId.equals(consentClientId) && scope.equals(consentScopes)) {
                            return true;
                        }
                    }
                } else {
                    if (logger.messageEnabled()) {
                        logger.message("No existing saved consent value for resourceOwner: " + resourceOwner.getId() + " in attribute:" + consentAttribute + " in realm:" + realm);
                    }
                }
            }
        } else {
            logger.error("No saved consent attribute defined in realm:" + realm);
        }
    } catch (Exception e) {
        logger.error("There was a problem getting the saved consent from the attribute: " + consentAttribute + " for realm:" + realm, e);
    }
    return false;
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) JSONException(org.json.JSONException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) UnsupportedResponseTypeException(org.forgerock.oauth2.core.exceptions.UnsupportedResponseTypeException) SSOException(com.iplanet.sso.SSOException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) InvalidScopeException(org.forgerock.oauth2.core.exceptions.InvalidScopeException)

Example 2 with ResourceOwner

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

the class OpenAMTokenStore method createDeviceCode.

/**
     * {@inheritDoc}
     */
public DeviceCode createDeviceCode(Set<String> scope, ResourceOwner resourceOwner, String clientId, String nonce, String responseType, String state, String acrValues, String prompt, String uiLocales, String loginHint, Integer maxAge, String claims, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws ServerException, NotFoundException {
    logger.message("DefaultOAuthTokenStoreImpl::Creating Authorization code");
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String deviceCode = UUID.randomUUID().toString();
    final StringBuilder codeBuilder = new StringBuilder(CODE_LENGTH);
    String userCode = null;
    int i;
    for (i = 0; i < NUM_RETRIES; i++) {
        for (int k = 0; k < CODE_LENGTH; k++) {
            codeBuilder.append(ALPHABET.charAt(secureRandom.nextInt(ALPHABET.length())));
        }
        try {
            readDeviceCode(codeBuilder.toString(), request);
            codeBuilder.delete(0, codeBuilder.length());
        // code can be found - try again
        } catch (InvalidGrantException e) {
            // Good, it doesn't exist yet.
            userCode = codeBuilder.toString();
            break;
        } catch (ServerException e) {
            logger.message("Could not query CTS, assume duplicate to be safe", e);
        }
    }
    if (i == NUM_RETRIES) {
        throw new ServerException("Could not generate a unique user code");
    }
    long expiryTime = System.currentTimeMillis() + (1000 * providerSettings.getDeviceCodeLifetime());
    String resourceOwnerId = resourceOwner == null ? null : resourceOwner.getId();
    final DeviceCode code = new DeviceCode(deviceCode, userCode, resourceOwnerId, clientId, nonce, responseType, state, acrValues, prompt, uiLocales, loginHint, maxAge, claims, expiryTime, scope, realmNormaliser.normalise(request.<String>getParameter(REALM)), codeChallenge, codeChallengeMethod);
    // Store in CTS
    try {
        tokenStore.create(code);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_DEVICE_CODE", code.toString() };
            auditLogger.logAccessMessage("CREATED_DEVICE_CODE", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_DEVICE_CODE", code.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_DEVICE_CODE", obs, null);
        }
        logger.error("Unable to create device code " + code, e);
        throw new ServerException("Could not create token in CTS");
    }
    request.setToken(DeviceCode.class, code);
    return code;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) DeviceCode(org.forgerock.oauth2.core.DeviceCode) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 3 with ResourceOwner

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

the class OpenAMOAuth2ProviderSettings method saveConsent.

/**
     * {@inheritDoc}
     */
public void saveConsent(ResourceOwner resourceOwner, String clientId, Set<String> scope) {
    String consentAttribute = null;
    try {
        consentAttribute = getStringSetting(realm, OAuth2ProviderService.SAVED_CONSENT_ATTRIBUTE);
        if (consentAttribute != null) {
            AMIdentity id = ((OpenAMResourceOwner) resourceOwner).getIdentity();
            //get the current set of consents and add our new consent to it if they exist.
            Set<String> existing = id.getAttribute(consentAttribute);
            Set<String> consents = (existing != null) ? new HashSet<String>(existing) : new HashSet<String>(1);
            StringBuilder sb = new StringBuilder();
            if (scope == null || scope.isEmpty()) {
                sb.append(clientId.trim()).append(" ");
            } else {
                sb.append(clientId.trim()).append(" ").append(joinScope(scope));
            }
            consents.add(sb.toString());
            if (logger.messageEnabled()) {
                logger.message("Saving consents:" + consents + " for resourceOwner: " + resourceOwner.getId() + " in attribute:" + consentAttribute + " in realm:" + realm);
            }
            updateConsentValues(consentAttribute, id, consents);
        } else {
            logger.error("Cannot save consent as no saved consent attribute defined in realm:" + realm);
        }
    } catch (Exception e) {
        logger.error("There was a problem saving the consent into the attribute: {} for realm: {}", consentAttribute, realm, e);
    }
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) JSONException(org.json.JSONException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) UnsupportedResponseTypeException(org.forgerock.oauth2.core.exceptions.UnsupportedResponseTypeException) SSOException(com.iplanet.sso.SSOException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) InvalidScopeException(org.forgerock.oauth2.core.exceptions.InvalidScopeException)

Example 4 with ResourceOwner

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

the class OpenAMResourceOwnerAuthenticator method authenticate.

/**
     * {@inheritDoc}
     */
public ResourceOwner authenticate(OAuth2Request request, boolean useSession) throws NotFoundException {
    SSOToken token = null;
    try {
        SSOTokenManager mgr = SSOTokenManager.getInstance();
        token = mgr.createSSOToken(ServletUtils.getRequest(request.<Request>getRequest()));
    } catch (Exception e) {
        logger.warning("No SSO Token in request", e);
    }
    if (token == null || !useSession) {
        final String username = request.getParameter(USERNAME);
        final char[] password = request.getParameter(PASSWORD) == null ? null : request.<String>getParameter(PASSWORD).toCharArray();
        final String realm = realmNormaliser.normalise(request.<String>getParameter(OAuth2Constants.Custom.REALM));
        final String authChain = request.getParameter(AUTH_CHAIN);
        return authenticate(username, password, realm, authChain);
    } else {
        try {
            final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
            long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
            return new OpenAMResourceOwner(id.getName(), id, authTime);
        } catch (SSOException e) {
            logger.error("Unable to create ResourceOwner", e);
        } catch (ParseException e) {
            logger.error("Unable to create ResourceOwner", e);
        } catch (IdRepoException e) {
            logger.error("Unable to create ResourceOwner", e);
        }
    }
    return null;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) ParseException(java.text.ParseException) IdRepoException(com.sun.identity.idm.IdRepoException) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 5 with ResourceOwner

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

the class OpenAMTokenStore method createAuthorizationCode.

/**
     * {@inheritDoc}
     */
public AuthorizationCode createAuthorizationCode(Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws ServerException, NotFoundException {
    logger.message("DefaultOAuthTokenStoreImpl::Creating Authorization code");
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String code = UUID.randomUUID().toString();
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAuthorizationCodeLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAuthorizationCodeLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final String ssoTokenId = getSsoTokenId(request);
    final OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(code, resourceOwner.getId(), clientId, redirectUri, scope, getClaimsFromRequest(request), expiryTime, nonce, realmNormaliser.normalise(request.<String>getParameter(REALM)), getAuthModulesFromSSOToken(request), getAuthenticationContextClassReferenceFromRequest(request), ssoTokenId, codeChallenge, codeChallengeMethod);
    // Store in CTS
    try {
        tokenStore.create(authorizationCode);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_AUTHORIZATION_CODE", authorizationCode.toString() };
            auditLogger.logAccessMessage("CREATED_AUTHORIZATION_CODE", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_AUTHORIZATION_CODE", authorizationCode.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_AUTHORIZATION_CODE", obs, null);
        }
        logger.error("Unable to create authorization code " + authorizationCode.getTokenInfo(), e);
        throw new ServerException("Could not create token in CTS");
    }
    request.setToken(AuthorizationCode.class, authorizationCode);
    return authorizationCode;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) 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