Search in sources :

Example 11 with OAuth2ProviderSettings

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

the class OpenAMScopeValidator method getUpdatedAt.

private String getUpdatedAt(String username, String realm, OAuth2Request request) throws NotFoundException {
    try {
        final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
        String modifyTimestampAttributeName;
        String createdTimestampAttributeName;
        try {
            modifyTimestampAttributeName = providerSettings.getModifiedTimestampAttributeName();
            createdTimestampAttributeName = providerSettings.getCreatedTimestampAttributeName();
        } catch (ServerException e) {
            logger.error("Unable to read last modified attribute from datastore", e);
            return DEFAULT_TIMESTAMP;
        }
        if (modifyTimestampAttributeName == null && createdTimestampAttributeName == null) {
            return null;
        }
        final AMHashMap timestamps = getTimestamps(username, realm, modifyTimestampAttributeName, createdTimestampAttributeName);
        final String modifyTimestamp = CollectionHelper.getMapAttr(timestamps, modifyTimestampAttributeName);
        if (modifyTimestamp != null) {
            synchronized (TIMESTAMP_DATE_FORMAT) {
                return Long.toString(TIMESTAMP_DATE_FORMAT.parse(modifyTimestamp).getTime() / 1000);
            }
        } else {
            final String createTimestamp = CollectionHelper.getMapAttr(timestamps, createdTimestampAttributeName);
            if (createTimestamp != null) {
                synchronized (TIMESTAMP_DATE_FORMAT) {
                    return Long.toString(TIMESTAMP_DATE_FORMAT.parse(createTimestamp).getTime() / 1000);
                }
            } else {
                return DEFAULT_TIMESTAMP;
            }
        }
    } catch (IdRepoException e) {
        if (logger.errorEnabled()) {
            logger.error("ScopeValidatorImpl" + ".getUpdatedAt: " + "error searching Identities with username : " + username, e);
        }
    } catch (SSOException e) {
        logger.warning("Error getting updatedAt attribute", e);
    } catch (ParseException e) {
        logger.warning("Error getting updatedAt attribute", e);
    }
    return null;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) ParseException(java.text.ParseException)

Example 12 with OAuth2ProviderSettings

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

the class OpenAMScopeValidator method getUserInfo.

/**
     * {@inheritDoc}
     */
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
    Map<String, Object> response = new HashMap<>();
    Bindings scriptVariables = new SimpleBindings();
    SSOToken ssoToken = getUsersSession(request);
    String realm;
    Set<String> scopes;
    AMIdentity id;
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
    try {
        if (token != null) {
            OpenIdConnectClientRegistration clientRegistration;
            try {
                clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
            } catch (InvalidClientException e) {
                logger.message("Unable to retrieve client from store.");
                throw new NotFoundException("No valid client registration found.");
            }
            final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
            //data comes from token when we have one
            realm = token.getRealm();
            scopes = token.getScope();
            id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
            response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
            response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
        } else {
            //otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
            realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
            id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
            String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
            scopes = splitScope(scopeStr);
        }
        scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
        scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
        scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
        scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
        scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
        scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
        ScriptObject script = getOIDCClaimsExtensionScript(realm);
        try {
            return scriptEvaluator.evaluateScript(script, scriptVariables);
        } catch (ScriptException e) {
            logger.message("Error running OIDC claims script", e);
            throw new ServerException("Error running OIDC claims script: " + e.getMessage());
        }
    } catch (ServerException e) {
        //API does not allow ServerExceptions to be thrown!
        throw new NotFoundException(e.getMessage());
    } catch (SSOException e) {
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) SSOException(com.iplanet.sso.SSOException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AMIdentity(com.sun.identity.idm.AMIdentity) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 13 with OAuth2ProviderSettings

use of org.forgerock.oauth2.core.OAuth2ProviderSettings 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)

Example 14 with OAuth2ProviderSettings

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

the class OpenAMTokenStore method generateAtHash.

/**
     * For at_hash values, used when token and id_token exist in scope.
     */
private String generateAtHash(String algorithm, OAuth2Request request, OAuth2ProviderSettings providerSettings) throws ServerException {
    final AccessToken accessToken = request.getToken(AccessToken.class);
    if (accessToken == null) {
        logger.message("at_hash generation requires an existing access_token.");
        return null;
    }
    final String accessTokenValue = ((String) accessToken.getTokenInfo().get(OAuth2Constants.Params.ACCESS_TOKEN));
    return generateHash(algorithm, accessTokenValue, providerSettings);
}
Also used : AccessToken(org.forgerock.oauth2.core.AccessToken)

Example 15 with OAuth2ProviderSettings

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

the class OpenAMTokenStore method generateCHash.

/**
     * For c_hash, used when code and id_token exist in scope.
     */
private String generateCHash(String algorithm, OAuth2Request request, OAuth2ProviderSettings providerSettings) throws ServerException {
    final AuthorizationCode authorizationCode = request.getToken(AuthorizationCode.class);
    if (authorizationCode == null) {
        logger.message("c_hash generation requires an existing code.");
        return null;
    }
    final String codeValue = authorizationCode.getTokenId();
    return generateHash(algorithm, codeValue, providerSettings);
}
Also used : AuthorizationCode(org.forgerock.oauth2.core.AuthorizationCode)

Aggregations

OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)39 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)18 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)15 JsonValue (org.forgerock.json.JsonValue)9 AccessToken (org.forgerock.oauth2.core.AccessToken)9 HashSet (java.util.HashSet)8 OAuth2Uris (org.forgerock.oauth2.core.OAuth2Uris)8 HashMap (java.util.HashMap)7 ResourceSetStore (org.forgerock.oauth2.resources.ResourceSetStore)7 Request (org.restlet.Request)7 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)6 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)6 JSONObject (org.json.JSONObject)6 Test (org.testng.annotations.Test)6 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)5 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)5 OpenIdConnectClientRegistration (org.forgerock.openidconnect.OpenIdConnectClientRegistration)5 BeforeTest (org.testng.annotations.BeforeTest)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 OAuth2ProviderSettingsFactory (org.forgerock.oauth2.core.OAuth2ProviderSettingsFactory)4