Search in sources :

Example 1 with AbstractCryptoProvider

use of org.xdi.oxauth.model.crypto.AbstractCryptoProvider in project oxAuth by GluuFederation.

the class IdTokenFactory method generateEncryptedIdToken.

public Jwe generateEncryptedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes, boolean includeIdTokenClaims) throws Exception {
    Jwe jwe = new Jwe();
    // Header
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseAlg());
    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseEnc());
    jwe.getHeader().setType(JwtType.JWT);
    jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
    jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
    // Claims
    jwe.getClaims().setIssuer(appConfiguration.getIssuer());
    jwe.getClaims().setAudience(authorizationGrant.getClient().getClientId());
    int lifeTime = appConfiguration.getIdTokenLifetime();
    Calendar calendar = Calendar.getInstance();
    Date issuedAt = calendar.getTime();
    calendar.add(Calendar.SECOND, lifeTime);
    Date expiration = calendar.getTime();
    jwe.getClaims().setExpirationTime(expiration);
    jwe.getClaims().setIssuedAt(issuedAt);
    if (authorizationGrant.getAcrValues() != null) {
        jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues());
        setAmrClaim(jwe, authorizationGrant.getAcrValues());
    }
    if (StringUtils.isNotBlank(nonce)) {
        jwe.getClaims().setClaim(JwtClaimName.NONCE, nonce);
    }
    if (authorizationGrant.getAuthenticationTime() != null) {
        jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime());
    }
    if (authorizationCode != null) {
        String codeHash = authorizationCode.getHash(null);
        jwe.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash);
    }
    if (accessToken != null) {
        String accessTokenHash = accessToken.getHash(null);
        jwe.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash);
    }
    jwe.getClaims().setClaim(JwtClaimName.OX_OPENID_CONNECT_VERSION, appConfiguration.getOxOpenIdConnectVersion());
    List<org.xdi.oxauth.model.common.Scope> dynamicScopes = Lists.newArrayList();
    if (includeIdTokenClaims) {
        for (String scopeName : scopes) {
            org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName);
            if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) {
                dynamicScopes.add(scope);
                continue;
            }
            if (scope != null && scope.getOxAuthClaims() != null) {
                for (String claimDn : scope.getOxAuthClaims()) {
                    GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn);
                    String claimName = gluuAttribute.getOxAuthClaimName();
                    String ldapName = gluuAttribute.getName();
                    String attributeValue;
                    if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) {
                        if (ldapName.equals("uid")) {
                            attributeValue = authorizationGrant.getUser().getUserId();
                        } else {
                            attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName());
                        }
                        jwe.getClaims().setClaim(claimName, attributeValue);
                    }
                }
            }
        }
    }
    if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) {
        for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) {
            // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
            boolean optional = true;
            GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
            if (gluuAttribute != null) {
                String ldapClaimName = gluuAttribute.getName();
                Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional);
                if (attribute != null) {
                    if (attribute instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) attribute;
                        List<String> values = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String value = jsonArray.optString(i);
                            if (value != null) {
                                values.add(value);
                            }
                        }
                        jwe.getClaims().setClaim(claim.getName(), values);
                    } else {
                        String value = (String) attribute;
                        jwe.getClaims().setClaim(claim.getName(), value);
                    }
                }
            }
        }
    }
    // Check for Subject Identifier Type
    if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) {
        String sectorIdentifierUri;
        if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) {
            sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri();
        } else {
            sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0];
        }
        String userInum = authorizationGrant.getUser().getAttribute("inum");
        PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier(userInum, sectorIdentifierUri);
        if (pairwiseIdentifier == null) {
            pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri);
            pairwiseIdentifier.setId(UUID.randomUUID().toString());
            pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseIdentifier.getId(), userInum));
            pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier);
        }
        jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId());
    } else {
        String openidSubAttribute = appConfiguration.getOpenidSubAttribute();
        if (openidSubAttribute.equals("uid")) {
            jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getUserId());
        } else {
            jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute));
        }
    }
    if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
        final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
        DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwe, unmodifiableAuthorizationGrant);
        externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
    }
    // Encryption
    if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
        JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(authorizationGrant.getClient().getJwksUri());
        AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
        String keyId = cryptoProvider.getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), SignatureAlgorithm.RS256);
        PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys);
        if (publicKey != null) {
            JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey);
            jwe = jweEncrypter.encrypt(jwe);
        } else {
            throw new InvalidJweException("The public key is not valid");
        }
    } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
        try {
            byte[] sharedSymmetricKey = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret()).getBytes(Util.UTF8_STRING_ENCODING);
            JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey);
            jwe = jweEncrypter.encrypt(jwe);
        } catch (UnsupportedEncodingException e) {
            throw new InvalidJweException(e);
        } catch (StringEncrypter.EncryptionException e) {
            throw new InvalidJweException(e);
        } catch (Exception e) {
            throw new InvalidJweException(e);
        }
    }
    return jwe;
}
Also used : BlockEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) PairwiseIdentifier(org.xdi.oxauth.model.ldap.PairwiseIdentifier) org.xdi.oxauth.model.common(org.xdi.oxauth.model.common) Jwe(org.xdi.oxauth.model.jwe.Jwe) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider) JweEncrypter(org.xdi.oxauth.model.jwe.JweEncrypter) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) PublicKey(java.security.PublicKey) JSONArray(org.codehaus.jettison.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DynamicScopeExternalContext(org.xdi.oxauth.service.external.context.DynamicScopeExternalContext) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GluuAttribute(org.xdi.model.GluuAttribute) JSONObject(org.codehaus.jettison.json.JSONObject) KeyEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) JwtSubClaimObject(org.xdi.oxauth.model.jwt.JwtSubClaimObject) JSONObject(org.codehaus.jettison.json.JSONObject) JweEncrypterImpl(org.xdi.oxauth.model.jwe.JweEncrypterImpl) Claim(org.xdi.oxauth.model.authorize.Claim)

Example 2 with AbstractCryptoProvider

use of org.xdi.oxauth.model.crypto.AbstractCryptoProvider in project oxAuth by GluuFederation.

the class JwtAuthorizationRequest method validateSignature.

private boolean validateSignature(SignatureAlgorithm signatureAlgorithm, Client client, String signingInput, String signature) throws Exception {
    ClientService clientService = CdiUtil.bean(ClientService.class);
    String sharedSecret = clientService.decryptSecret(client.getClientSecret());
    JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
    AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
    boolean validSignature = cryptoProvider.verifySignature(signingInput, signature, keyId, jwks, sharedSecret, signatureAlgorithm);
    return validSignature;
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) ClientService(org.xdi.oxauth.service.ClientService) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider)

Example 3 with AbstractCryptoProvider

use of org.xdi.oxauth.model.crypto.AbstractCryptoProvider in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method getJwtResponse.

public String getJwtResponse(SignatureAlgorithm signatureAlgorithm, User user, AuthorizationGrant authorizationGrant, Collection<String> scopes) throws Exception {
    Jwt jwt = new Jwt();
    AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
    // Header
    jwt.getHeader().setType(JwtType.JWT);
    jwt.getHeader().setAlgorithm(signatureAlgorithm);
    String keyId = cryptoProvider.getKeyId(webKeysConfiguration, signatureAlgorithm);
    if (keyId != null) {
        jwt.getHeader().setKeyId(keyId);
    }
    // Claims
    List<Scope> dynamicScopes = new ArrayList<Scope>();
    for (String scopeName : scopes) {
        Scope scope = scopeService.getScopeByDisplayName(scopeName);
        if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) {
            dynamicScopes.add(scope);
            continue;
        }
        if (scope.getOxAuthClaims() != null) {
            for (String claimDn : scope.getOxAuthClaims()) {
                GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn);
                String claimName = gluuAttribute.getOxAuthClaimName();
                String ldapName = gluuAttribute.getName();
                String attributeValue = null;
                if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) {
                    if (ldapName.equals("uid")) {
                        attributeValue = user.getUserId();
                    } else {
                        attributeValue = user.getAttribute(gluuAttribute.getName());
                    }
                    jwt.getClaims().setClaim(claimName, attributeValue);
                }
            }
        }
    }
    if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember() != null) {
        for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember().getClaims()) {
            // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
            boolean optional = true;
            GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
            if (gluuAttribute != null) {
                String ldapClaimName = gluuAttribute.getName();
                Object attribute = user.getAttribute(ldapClaimName, optional);
                if (attribute != null) {
                    if (attribute instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) attribute;
                        List<String> values = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String value = jsonArray.optString(i);
                            if (value != null) {
                                values.add(value);
                            }
                        }
                        jwt.getClaims().setClaim(claim.getName(), values);
                    } else {
                        String value = (String) attribute;
                        jwt.getClaims().setClaim(claim.getName(), value);
                    }
                }
            }
        }
    }
    // Check for Subject Identifier Type
    if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) {
        String sectorIdentifierUri = null;
        if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) {
            sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri();
        } else {
            sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0];
        }
        String userInum = authorizationGrant.getUser().getAttribute("inum");
        PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier(userInum, sectorIdentifierUri);
        if (pairwiseIdentifier == null) {
            pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri);
            pairwiseIdentifier.setId(UUID.randomUUID().toString());
            pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseIdentifier.getId(), userInum));
            pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier);
        }
        jwt.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId());
    } else {
        String openidSubAttribute = appConfiguration.getOpenidSubAttribute();
        jwt.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute));
    }
    // If signed, the UserInfo Response SHOULD contain the Claims iss (issuer) and aud (audience) as members. The iss value should be the OP's Issuer Identifier URL. The aud value should be or include the RP's Client ID value.
    jwt.getClaims().setIssuer(appConfiguration.getIssuer());
    jwt.getClaims().setAudience(authorizationGrant.getClientId());
    if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
        final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
        DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwt, unmodifiableAuthorizationGrant);
        externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
    }
    // Signature
    String sharedSecret = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret());
    String signature = cryptoProvider.sign(jwt.getSigningInput(), jwt.getHeader().getKeyId(), sharedSecret, signatureAlgorithm);
    jwt.setEncodedSignature(signature);
    return jwt.toString();
}
Also used : Jwt(org.xdi.oxauth.model.jwt.Jwt) JSONArray(org.codehaus.jettison.json.JSONArray) DynamicScopeExternalContext(org.xdi.oxauth.service.external.context.DynamicScopeExternalContext) GluuAttribute(org.xdi.model.GluuAttribute) PairwiseIdentifier(org.xdi.oxauth.model.ldap.PairwiseIdentifier) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider) JwtSubClaimObject(org.xdi.oxauth.model.jwt.JwtSubClaimObject) JSONObject(org.codehaus.jettison.json.JSONObject) Claim(org.xdi.oxauth.model.authorize.Claim)

Example 4 with AbstractCryptoProvider

use of org.xdi.oxauth.model.crypto.AbstractCryptoProvider in project oxAuth by GluuFederation.

the class SubjectIdentifierGenerator method generatePairwiseSubjectIdentifier.

public static String generatePairwiseSubjectIdentifier(String sectorIdentifier, String localAccountId, String key, String salt, AppConfiguration configuration) throws Exception {
    AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(configuration);
    String signingInput = sectorIdentifier + localAccountId + salt;
    return cryptoProvider.sign(signingInput, null, key, SignatureAlgorithm.HS256);
}
Also used : AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider)

Example 5 with AbstractCryptoProvider

use of org.xdi.oxauth.model.crypto.AbstractCryptoProvider in project oxAuth by GluuFederation.

the class KeyGeneratorTimer method updateKeys.

private JSONObject updateKeys(JSONObject jwks) throws Exception {
    JSONObject jsonObject = AbstractCryptoProvider.generateJwks(appConfiguration.getKeyRegenerationInterval(), appConfiguration.getIdTokenLifetime(), appConfiguration);
    JSONArray keys = jwks.getJSONArray(JSON_WEB_KEY_SET);
    for (int i = 0; i < keys.length(); i++) {
        JSONObject key = keys.getJSONObject(i);
        if (key.has(EXPIRATION_TIME) && !key.isNull(EXPIRATION_TIME)) {
            GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            GregorianCalendar expirationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            expirationDate.setTimeInMillis(key.getLong(EXPIRATION_TIME));
            if (expirationDate.before(now)) {
                // The expired key is not added to the array of keys
                log.debug("Removing JWK: {}, Expiration date: {}", key.getString(KEY_ID), key.getString(EXPIRATION_TIME));
                AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
                cryptoProvider.deleteKey(key.getString(KEY_ID));
            } else {
                jsonObject.getJSONArray(JSON_WEB_KEY_SET).put(key);
            }
        } else {
            GregorianCalendar expirationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            expirationTime.add(GregorianCalendar.HOUR, appConfiguration.getKeyRegenerationInterval());
            expirationTime.add(GregorianCalendar.SECOND, appConfiguration.getIdTokenLifetime());
            key.put(EXPIRATION_TIME, expirationTime.getTimeInMillis());
            jsonObject.getJSONArray(JSON_WEB_KEY_SET).put(key);
        }
    }
    return jsonObject;
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) GregorianCalendar(java.util.GregorianCalendar) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider)

Aggregations

AbstractCryptoProvider (org.xdi.oxauth.model.crypto.AbstractCryptoProvider)7 JSONObject (org.codehaus.jettison.json.JSONObject)6 JSONArray (org.codehaus.jettison.json.JSONArray)4 GluuAttribute (org.xdi.model.GluuAttribute)3 Claim (org.xdi.oxauth.model.authorize.Claim)3 JwtSubClaimObject (org.xdi.oxauth.model.jwt.JwtSubClaimObject)3 PairwiseIdentifier (org.xdi.oxauth.model.ldap.PairwiseIdentifier)3 DynamicScopeExternalContext (org.xdi.oxauth.service.external.context.DynamicScopeExternalContext)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 PublicKey (java.security.PublicKey)2 InvalidJweException (org.xdi.oxauth.model.exception.InvalidJweException)2 InvalidJwtException (org.xdi.oxauth.model.exception.InvalidJwtException)2 Jwe (org.xdi.oxauth.model.jwe.Jwe)2 JweEncrypter (org.xdi.oxauth.model.jwe.JweEncrypter)2 JweEncrypterImpl (org.xdi.oxauth.model.jwe.JweEncrypterImpl)2 ClientService (org.xdi.oxauth.service.ClientService)2 SignatureException (java.security.SignatureException)1 Date (java.util.Date)1 GregorianCalendar (java.util.GregorianCalendar)1 EntryPersistenceException (org.gluu.site.ldap.persistence.exception.EntryPersistenceException)1