Search in sources :

Example 1 with JwtSigner

use of org.gluu.oxauth.model.token.JwtSigner in project oxAuth by GluuFederation.

the class IntrospectionWebService method createResponseAsJwt.

private String createResponseAsJwt(JSONObject response, AuthorizationGrant grant) throws Exception {
    final JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, grant.getClient());
    final Jwt jwt = jwtSigner.newJwt();
    Audience.setAudience(jwt.getClaims(), grant.getClient());
    Iterator<String> keysIter = response.keys();
    while (keysIter.hasNext()) {
        String key = keysIter.next();
        Object value = response.opt(key);
        if (value != null) {
            try {
                jwt.getClaims().setClaimObject(key, value, false);
            } catch (Exception e) {
                log.error("Failed to put claims into jwt. Key: " + key + ", response: " + response.toString(), e);
            }
        }
    }
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 2 with JwtSigner

use of org.gluu.oxauth.model.token.JwtSigner in project oxAuth by GluuFederation.

the class UmaRptService method createRptJwt.

private String createRptJwt(ExecutionContext executionContext, List<UmaPermission> permissions, Date creationDate, Date expirationDate) throws Exception {
    Client client = executionContext.getClient();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("client_id", client.getClientId());
    jwt.getClaims().setExpirationTime(expirationDate);
    jwt.getClaims().setIssuedAt(creationDate);
    Audience.setAudience(jwt.getClaims(), client);
    if (permissions != null && !permissions.isEmpty()) {
        String pctCode = permissions.iterator().next().getAttributes().get(UmaPermission.PCT);
        if (StringHelper.isNotEmpty(pctCode)) {
            UmaPCT pct = pctService.getByCode(pctCode);
            if (pct != null) {
                jwt.getClaims().setClaim("pct_claims", pct.getClaims().toJsonObject());
            } else {
                log.error("Failed to find PCT with code: " + pctCode + " which is taken from permission object: " + permissions.iterator().next().getDn());
            }
        }
        jwt.getClaims().setClaim("permissions", buildPermissionsJSONObject(permissions));
    }
    runScriptAndInjectValuesIntoJwt(jwt, executionContext);
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) UmaPCT(org.gluu.oxauth.uma.authorization.UmaPCT) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Client(org.gluu.oxauth.model.registration.Client)

Example 3 with JwtSigner

use of org.gluu.oxauth.model.token.JwtSigner in project oxAuth by GluuFederation.

the class CrossEncryptionTest method nestedJWTProducedByGluu.

@Test
public void nestedJWTProducedByGluu() throws Exception {
    AppConfiguration appConfiguration = new AppConfiguration();
    List<JSONWebKey> keyArrayList = new ArrayList<JSONWebKey>();
    keyArrayList.add(getSenderWebKey());
    JSONWebKeySet keySet = new JSONWebKeySet();
    keySet.setKeys(keyArrayList);
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, keySet, SignatureAlgorithm.RS256, "audience", null, new AbstractCryptoProvider() {

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use) throws Exception {
            return null;
        }

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use, int keyLength) throws Exception {
            return null;
        }

        @Override
        public boolean containsKey(String keyId) {
            return false;
        }

        @Override
        public String sign(String signingInput, String keyId, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
            RSAPrivateKey privateKey = ((RSAKey) JWK.parse(senderJwkJson)).toRSAPrivateKey();
            Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
            signature.initSign(privateKey);
            signature.update(signingInput.getBytes());
            return Base64Util.base64urlencode(signature.sign());
        }

        @Override
        public boolean verifySignature(String signingInput, String encodedSignature, String keyId, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
            return false;
        }

        @Override
        public boolean deleteKey(String keyId) throws Exception {
            return false;
        }

        @Override
        public PrivateKey getPrivateKey(String keyId) throws Exception {
            throw new UnsupportedOperationException("Method not implemented.");
        }
    });
    Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setSubjectIdentifier("testing");
    jwt.getClaims().setIssuer("https:devgluu.saminet.local");
    jwt = jwtSigner.sign();
    RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));
    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
    Jwe jwe = new Jwe();
    jwe.getHeader().setType(JwtType.JWT);
    jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
    jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
    jwe.getHeader().setKeyId("1");
    jwe.setSignedJWTPayload(jwt);
    JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
    String jweString = encrypter.encrypt(jwe).toString();
    decryptAndValidateSignatureWithGluu(jweString);
    decryptAndValidateSignatureWithNimbus(jweString);
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) JSONWebKeySet(org.gluu.oxauth.model.jwk.JSONWebKeySet) ArrayList(java.util.ArrayList) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JwtSigner(org.gluu.oxauth.model.token.JwtSigner) AppConfiguration(org.gluu.oxauth.model.configuration.AppConfiguration) Jwe(org.gluu.oxauth.model.jwe.Jwe) AbstractCryptoProvider(org.gluu.oxauth.model.crypto.AbstractCryptoProvider) Use(org.gluu.oxauth.model.jwk.Use) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) Algorithm(org.gluu.oxauth.model.jwk.Algorithm) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JSONException(org.json.JSONException) ParseException(java.text.ParseException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) JSONWebKey(org.gluu.oxauth.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) Signature(java.security.Signature) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) JweEncrypterImpl(org.gluu.oxauth.model.jwe.JweEncrypterImpl) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Test(org.testng.annotations.Test)

Example 4 with JwtSigner

use of org.gluu.oxauth.model.token.JwtSigner in project oxAuth by GluuFederation.

the class SessionIdService method generateJwt.

private Jwt generateJwt(SessionId sessionId, String audience) {
    try {
        JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, SignatureAlgorithm.RS512, audience);
        Jwt jwt = jwtSigner.newJwt();
        // claims
        jwt.getClaims().setClaim("id", sessionId.getId());
        jwt.getClaims().setClaim("authentication_time", sessionId.getAuthenticationTime());
        jwt.getClaims().setClaim("user_dn", sessionId.getUserDn());
        jwt.getClaims().setClaim("state", sessionId.getState() != null ? sessionId.getState().getValue() : "");
        jwt.getClaims().setClaim("session_attributes", JwtSubClaimObject.fromMap(sessionId.getSessionAttributes()));
        jwt.getClaims().setClaim("last_used_at", sessionId.getLastUsedAt());
        jwt.getClaims().setClaim("permission_granted", sessionId.getPermissionGranted());
        jwt.getClaims().setClaim("permission_granted_map", JwtSubClaimObject.fromBooleanMap(sessionId.getPermissionGrantedMap().getPermissionGranted()));
        // sign
        return jwtSigner.sign();
    } catch (Exception e) {
        log.error("Failed to sign session jwt! " + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) InvalidSessionStateException(org.gluu.oxauth.model.exception.InvalidSessionStateException) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) LDAPException(com.unboundid.ldap.sdk.LDAPException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 5 with JwtSigner

use of org.gluu.oxauth.model.token.JwtSigner in project oxAuth by GluuFederation.

the class AuthorizationGrant method createAccessTokenAsJwt.

private String createAccessTokenAsJwt(AccessToken accessToken, ExecutionContext context) throws Exception {
    final User user = getUser();
    final Client client = getClient();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("scope", Lists.newArrayList(getScopes()));
    jwt.getClaims().setClaim("client_id", getClientId());
    jwt.getClaims().setClaim("username", user != null ? user.getAttribute("displayName") : null);
    jwt.getClaims().setClaim("token_type", accessToken.getTokenType().getName());
    // guarantee uniqueness : without it we can get race condition
    jwt.getClaims().setClaim("code", accessToken.getCode());
    jwt.getClaims().setExpirationTime(accessToken.getExpirationDate());
    jwt.getClaims().setIssuedAt(accessToken.getCreationDate());
    jwt.getClaims().setSubjectIdentifier(getSub());
    jwt.getClaims().setClaim("x5t#S256", accessToken.getX5ts256());
    Audience.setAudience(jwt.getClaims(), getClient());
    if (client.getAttributes().getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims()) {
        runIntrospectionScriptAndInjectValuesIntoJwt(jwt, context);
    }
    final String accessTokenCode = jwtSigner.sign().toString();
    if (log.isTraceEnabled())
        log.trace("Created access token JWT: {}", accessTokenCode + ", claims: " + jwt.getClaims().toJsonString());
    return accessTokenCode;
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Client(org.gluu.oxauth.model.registration.Client)

Aggregations

Jwt (org.gluu.oxauth.model.jwt.Jwt)5 JwtSigner (org.gluu.oxauth.model.token.JwtSigner)5 SignatureAlgorithm (org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm)3 JSONException (org.json.JSONException)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Client (org.gluu.oxauth.model.registration.Client)2 JSONObject (org.json.JSONObject)2 RSAKey (com.nimbusds.jose.jwk.RSAKey)1 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 URISyntaxException (java.net.URISyntaxException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1 PrivateKey (java.security.PrivateKey)1 Signature (java.security.Signature)1 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 AppConfiguration (org.gluu.oxauth.model.configuration.AppConfiguration)1