Search in sources :

Example 11 with ServerException

use of org.forgerock.oauth2.core.exceptions.ServerException 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 12 with ServerException

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

the class OpenAMOAuth2UrisFactory method get.

/**
     * Gets a OAuth2Uris instance.
     *
     * @param context TODO
     * @param realmInfo The realm information.
     * @return A UmaProviderSettings instance.
     */
@Override
public OAuth2Uris get(Context context, RealmInfo realmInfo) throws NotFoundException, ServerException {
    String absoluteRealm = realmInfo.getAbsoluteRealm();
    BaseURLProvider baseURLProvider = baseURLProviderFactory.get(absoluteRealm);
    String baseUrl;
    try {
        baseUrl = baseURLProvider.getRealmURL(context.asContext(HttpContext.class), "/oauth2", absoluteRealm);
    } catch (InvalidBaseUrlException e) {
        throw new ServerException("Configuration error");
    }
    return get(absoluteRealm, baseUrl);
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) InvalidBaseUrlException(org.forgerock.openam.services.baseurl.InvalidBaseUrlException) BaseURLProvider(org.forgerock.openam.services.baseurl.BaseURLProvider)

Example 13 with ServerException

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

the class OpenAMScopeValidator method gatherRequestedClaims.

/**
     * Generates a map for the claims specifically requested as per Section 5.5 of the spec.
     * Ends up mapping requested claims against a set of their optional values (empty if
     * claim is requested but no suggested/required values given).
     */
private Map<String, Set<String>> gatherRequestedClaims(OAuth2ProviderSettings providerSettings, String claimsJson, String objectName) {
    final Map<String, Set<String>> requestedClaims = new HashMap<String, Set<String>>();
    try {
        if (providerSettings.getClaimsParameterSupported() && claimsJson != null) {
            try {
                final JSONObject claimsObject = new JSONObject(claimsJson);
                JSONObject subClaimsRequest = claimsObject.getJSONObject(objectName);
                Iterator<String> it = subClaimsRequest.keys();
                while (it.hasNext()) {
                    final String keyName = it.next();
                    JSONObject optObj = subClaimsRequest.optJSONObject(keyName);
                    final HashSet<String> options = new HashSet<String>();
                    if (optObj != null) {
                        final JSONArray optArray = optObj.optJSONArray(OAuth2Constants.Params.VALUES);
                        if (optArray != null) {
                            for (int i = 0; i < optArray.length(); i++) {
                                options.add(optArray.getString(i));
                            }
                        }
                        final String value = optObj.optString(OAuth2Constants.Params.VALUE);
                        if (!StringUtils.isBlank(value)) {
                            options.add(value);
                        }
                    }
                    requestedClaims.put(keyName, options);
                }
            } catch (JSONException e) {
            //ignorable
            }
        }
    } catch (ServerException e) {
        logger.message("Requested Claims Supported not set.");
    }
    return requestedClaims;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JSONObject(org.json.JSONObject) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) HashSet(java.util.HashSet)

Example 14 with ServerException

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

the class OpenAMScopeValidator method getOIDCClaimsExtensionScript.

private ScriptObject getOIDCClaimsExtensionScript(String realm) throws ServerException {
    OpenAMSettingsImpl settings = new OpenAMSettingsImpl(OAuth2Constants.OAuth2ProviderService.NAME, OAuth2Constants.OAuth2ProviderService.VERSION);
    try {
        String scriptId = settings.getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.OIDC_CLAIMS_EXTENSION_SCRIPT);
        if (EMPTY_SCRIPT_SELECTION.equals(scriptId)) {
            return new ScriptObject("oidc-claims-script", "", SupportedScriptingLanguage.JAVASCRIPT);
        }
        ScriptConfiguration config = getScriptConfiguration(realm, scriptId);
        return new ScriptObject(config.getName(), config.getScript(), config.getLanguage());
    } catch (org.forgerock.openam.scripting.ScriptException | SSOException | SMSException e) {
        logger.message("Error running OIDC claims script", e);
        throw new ServerException("Error running OIDC claims script: " + e.getMessage());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) ScriptException(javax.script.ScriptException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) OpenAMSettingsImpl(org.forgerock.openam.utils.OpenAMSettingsImpl) ScriptConfiguration(org.forgerock.openam.scripting.service.ScriptConfiguration) SSOException(com.iplanet.sso.SSOException)

Example 15 with ServerException

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

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)60 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)31 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)25 JsonValue (org.forgerock.json.JsonValue)18 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)18 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)14 HashMap (java.util.HashMap)13 AccessToken (org.forgerock.oauth2.core.AccessToken)13 HashSet (java.util.HashSet)12 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)11 ResourceSetStore (org.forgerock.oauth2.resources.ResourceSetStore)11 SSOException (com.iplanet.sso.SSOException)9 Request (org.restlet.Request)9 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)8 Map (java.util.Map)7 OAuth2Uris (org.forgerock.oauth2.core.OAuth2Uris)7 JSONObject (org.json.JSONObject)7 SMSException (com.sun.identity.sm.SMSException)6 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)6