Search in sources :

Example 66 with ServerException

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

the class OpenAMTokenStore method appendIdTokenClaims.

//return all claims from scopes + claims requested in the id_token
private void appendIdTokenClaims(OAuth2Request request, OAuth2ProviderSettings providerSettings, OpenAMOpenIdConnectToken oidcToken) throws ServerException, NotFoundException, InvalidClientException {
    try {
        AccessToken accessToken = request.getToken(AccessToken.class);
        Map<String, Object> userInfo = providerSettings.getUserInfo(accessToken, request).getValues();
        for (Map.Entry<String, Object> claim : userInfo.entrySet()) {
            oidcToken.put(claim.getKey(), claim.getValue());
        }
    } catch (UnauthorizedClientException e) {
        throw failureFactory.getException(request, e.getMessage());
    }
}
Also used : AccessToken(org.forgerock.oauth2.core.AccessToken) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JSONObject(org.json.JSONObject) Map(java.util.Map)

Example 67 with ServerException

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

the class OpenAMTokenStore method createAccessToken.

/**
     * {@inheritDoc}
     */
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final AccessToken accessToken;
    if (refreshToken == null) {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    } else {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    }
    try {
        tokenStore.create(accessToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_TOKEN", accessToken.toString() };
            auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        logger.error("Could not create token in CTS: " + e.getMessage());
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
        }
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(AccessToken.class, accessToken);
    return accessToken;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 68 with ServerException

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

the class OpenAMTokenStore method deleteDeviceCode.

@Override
public void deleteDeviceCode(String clientId, String code, OAuth2Request request) throws ServerException, NotFoundException, InvalidGrantException {
    try {
        readDeviceCode(clientId, code, request);
        tokenStore.delete(code);
    } catch (CoreTokenException e) {
        throw new ServerException("Could not delete user code state");
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException)

Example 69 with ServerException

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

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

the class OpenAMTokenStore method generateHash.

/**
     * Generates hash values, by hashing the valueToEncode using the requests's "alg"
     * parameter, then returning the base64url encoding of the
     * leftmost half of the returned bytes. Used for both at_hash and c_hash claims.
     */
private String generateHash(String algorithm, String valueToEncode, OAuth2ProviderSettings providerSettings) throws ServerException {
    if (!providerSettings.getSupportedIDTokenSigningAlgorithms().contains(algorithm)) {
        logger.message("Unsupported signing algorithm requested for hash value.");
        return null;
    }
    final JwsAlgorithm alg = JwsAlgorithm.valueOf(algorithm);
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(alg.getMdAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        logger.message("Unsupported signing algorithm chosen for hashing.");
        throw new ServerException("Algorithm not supported.");
    }
    final byte[] result = digest.digest(valueToEncode.getBytes(Utils.CHARSET));
    final byte[] toEncode = Arrays.copyOfRange(result, 0, result.length / 2);
    return Base64url.encode(toEncode);
}
Also used : JwsAlgorithm(org.forgerock.json.jose.jws.JwsAlgorithm) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

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