Search in sources :

Example 1 with JwtSigner

use of io.jans.as.server.model.token.JwtSigner in project jans by JanssenProject.

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) {
        if (log.isErrorEnabled())
            log.error("Failed to sign session jwt! " + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
Also used : JwtSigner(io.jans.as.server.model.token.JwtSigner) Jwt(io.jans.as.model.jwt.Jwt) InvalidSessionStateException(io.jans.as.server.model.exception.InvalidSessionStateException) URISyntaxException(java.net.URISyntaxException) FailedComputeSessionStateException(io.jans.as.server.service.exception.FailedComputeSessionStateException) JSONException(org.json.JSONException) AcrChangedException(io.jans.as.server.model.exception.AcrChangedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) LDAPException(com.unboundid.ldap.sdk.LDAPException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with JwtSigner

use of io.jans.as.server.model.token.JwtSigner in project jans by JanssenProject.

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());
    // DPoP
    final String dpop = context.getDpop();
    if (StringUtils.isNotBlank(dpop)) {
        jwt.getClaims().setNotBefore(accessToken.getCreationDate());
        JSONObject cnf = new JSONObject();
        cnf.put("jkt", dpop);
        jwt.getClaims().setClaim("cnf", cnf);
    }
    Audience.setAudience(jwt.getClaims(), getClient());
    if (isTrue(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(io.jans.as.server.model.token.JwtSigner) User(io.jans.as.common.model.common.User) JSONObject(org.json.JSONObject) Jwt(io.jans.as.model.jwt.Jwt) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Client(io.jans.as.common.model.registration.Client)

Example 3 with JwtSigner

use of io.jans.as.server.model.token.JwtSigner in project jans by JanssenProject.

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: {} which is taken from permission object: {}", pctCode, permissions.iterator().next().getDn());
            }
        }
        jwt.getClaims().setClaim("permissions", buildPermissionsJSONObject(permissions));
    }
    runScriptAndInjectValuesIntoJwt(jwt, executionContext);
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(io.jans.as.server.model.token.JwtSigner) UmaPCT(io.jans.as.server.uma.authorization.UmaPCT) Jwt(io.jans.as.model.jwt.Jwt) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Client(io.jans.as.common.model.registration.Client)

Example 4 with JwtSigner

use of io.jans.as.server.model.token.JwtSigner in project jans by JanssenProject.

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(io.jans.as.server.model.token.JwtSigner) Jwt(io.jans.as.model.jwt.Jwt) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 5 with JwtSigner

use of io.jans.as.server.model.token.JwtSigner in project jans by JanssenProject.

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) throws CryptoProviderException {
            return null;
        }

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

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

        @Override
        public String sign(String signingInput, String keyId, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws CryptoProviderException {
            try {
                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());
            } catch (JOSEException | ParseException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {
                throw new CryptoProviderException(e);
            }
        }

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

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

        @Override
        public PrivateKey getPrivateKey(String keyId) throws CryptoProviderException {
            throw new UnsupportedOperationException("Method not implemented.");
        }

        @Override
        public PublicKey getPublicKey(String keyId) {
            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(io.jans.as.model.jwk.JSONWebKeySet) ArrayList(java.util.ArrayList) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) JwtSigner(io.jans.as.server.model.token.JwtSigner) AppConfiguration(io.jans.as.model.configuration.AppConfiguration) Jwe(io.jans.as.model.jwe.Jwe) AbstractCryptoProvider(io.jans.as.model.crypto.AbstractCryptoProvider) PublicKey(java.security.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) Jwt(io.jans.as.model.jwt.Jwt) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) Signature(java.security.Signature) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) JweEncrypterImpl(io.jans.as.model.jwe.JweEncrypterImpl) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Test(org.testng.annotations.Test)

Aggregations

Jwt (io.jans.as.model.jwt.Jwt)5 JwtSigner (io.jans.as.server.model.token.JwtSigner)5 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)3 JSONObject (org.json.JSONObject)3 Client (io.jans.as.common.model.registration.Client)2 JSONException (org.json.JSONException)2 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RSAKey (com.nimbusds.jose.jwk.RSAKey)1 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 User (io.jans.as.common.model.common.User)1 AppConfiguration (io.jans.as.model.configuration.AppConfiguration)1 AbstractCryptoProvider (io.jans.as.model.crypto.AbstractCryptoProvider)1 BlockEncryptionAlgorithm (io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)1 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)1 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)1 CryptoProviderException (io.jans.as.model.exception.CryptoProviderException)1 Jwe (io.jans.as.model.jwe.Jwe)1 JweEncrypterImpl (io.jans.as.model.jwe.JweEncrypterImpl)1 Algorithm (io.jans.as.model.jwk.Algorithm)1