Search in sources :

Example 1 with BlockEncryptionAlgorithm

use of org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method requestUserInfo.

private Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (tokenService.isBearerAuthToken(authorization)) {
        accessToken = tokenService.getBearerToken(authorization);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            return response(400, UserInfoErrorResponseType.INVALID_REQUEST, "access token is not valid.");
        }
        AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (authorizationGrant == null) {
            log.trace("Failed to find authorization grant by access_token: " + accessToken);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
        final AbstractToken accessTokenObject = authorizationGrant.getAccessToken(accessToken);
        if (accessTokenObject == null || !accessTokenObject.isValid()) {
            log.trace("Invalid access token object, access_token: {}, isNull: {}, isValid: {}", accessToken, accessTokenObject == null, false);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Grant object has client_credentials grant_type which is not valid.");
        }
        if (appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Both openid and profile scopes are not present.");
        }
        if (!appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Missed openid scope.");
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
        builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
        builder.header("Pragma", "no-cache");
        User currentUser = authorizationGrant.getUser();
        try {
            currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
        } catch (EntryPersistenceException ex) {
            log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
        }
        if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
            KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
            BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
            builder.type("application/jwt");
            builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
            SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
            builder.type("application/jwt");
            builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else {
            builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
            builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
        }
        return builder.build();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // 500
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
    } finally {
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
    }
}
Also used : JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 2 with BlockEncryptionAlgorithm

use of org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm 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 3 with BlockEncryptionAlgorithm

use of org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm in project oxAuth by GluuFederation.

the class JwrService method encryptJwe.

private Jwe encryptJwe(Jwe jwe, Client client) throws Exception {
    if (appConfiguration.getUseNestedJwtDuringEncryption()) {
        JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, client);
        Jwt jwt = jwtSigner.newJwt();
        jwt.setClaims(jwe.getClaims());
        jwe.setSignedJWTPayload(signJwt(jwt, client));
    }
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(ALGORITHM));
    final BlockEncryptionAlgorithm encryptionMethod = jwe.getHeader().getEncryptionMethod();
    if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
        JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(client.getJwksUri());
        String keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), Algorithm.fromString(keyEncryptionAlgorithm.getName()), Use.ENCRYPTION);
        PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys, null);
        jwe.getHeader().setKeyId(keyId);
        if (publicKey == null) {
            throw new InvalidJweException("The public key is not valid");
        }
        JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, encryptionMethod, publicKey);
        return jweEncrypter.encrypt(jwe);
    }
    if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
        byte[] sharedSymmetricKey = clientService.decryptSecret(client.getClientSecret()).getBytes(StandardCharsets.UTF_8);
        JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, encryptionMethod, sharedSymmetricKey);
        return jweEncrypter.encrypt(jwe);
    }
    throw new IllegalArgumentException("Unsupported encryption algorithm: " + keyEncryptionAlgorithm);
}
Also used : ServerCryptoProvider(org.gluu.oxauth.service.ServerCryptoProvider) Jwt(org.gluu.oxauth.model.jwt.Jwt) PublicKey(java.security.PublicKey) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JSONObject(org.json.JSONObject) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) JweEncrypterImpl(org.gluu.oxauth.model.jwe.JweEncrypterImpl) JweEncrypter(org.gluu.oxauth.model.jwe.JweEncrypter) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException)

Example 4 with BlockEncryptionAlgorithm

use of org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm in project oxAuth by GluuFederation.

the class JwrService method createJwr.

public JsonWebResponse createJwr(Client client) {
    try {
        if (client.getIdTokenEncryptedResponseAlg() != null && client.getIdTokenEncryptedResponseEnc() != null) {
            Jwe jwe = new Jwe();
            // Header
            KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(client.getIdTokenEncryptedResponseAlg());
            BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(client.getIdTokenEncryptedResponseEnc());
            jwe.getHeader().setType(JwtType.JWT);
            jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
            jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
            return jwe;
        } else {
            JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, client);
            return jwtSigner.newJwt();
        }
    } catch (Exception e) {
        log.error("Failed to create logout_token.", e);
        return null;
    }
}
Also used : KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) Jwe(org.gluu.oxauth.model.jwe.Jwe) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 5 with BlockEncryptionAlgorithm

use of org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm in project oxAuth by GluuFederation.

the class CrossEncryptionTest method encryptWithGluuJweEncrypter.

private String encryptWithGluuJweEncrypter() {
    try {
        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.getClaims().setIssuer("https:devgluu.saminet.local");
        jwe.getClaims().setSubjectIdentifier("testing");
        jwe.getHeader().setKeyId("1");
        JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
        jwe = encrypter.encrypt(jwe);
        // System.out.println("EncodedIntegrityValue: " + jwe.getEncodedIntegrityValue());
        return jwe.toString();
    } catch (Exception e) {
        System.out.println("Error encryption with Gluu JweEncrypter: " + e.getMessage());
        return null;
    }
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) Jwe(org.gluu.oxauth.model.jwe.Jwe) JweEncrypterImpl(org.gluu.oxauth.model.jwe.JweEncrypterImpl) 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) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)

Aggregations

BlockEncryptionAlgorithm (org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)5 KeyEncryptionAlgorithm (org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm)5 InvalidJweException (org.gluu.oxauth.model.exception.InvalidJweException)5 Jwe (org.gluu.oxauth.model.jwe.Jwe)3 JweEncrypterImpl (org.gluu.oxauth.model.jwe.JweEncrypterImpl)3 RSAKey (com.nimbusds.jose.jwk.RSAKey)2 IOException (java.io.IOException)2 ParseException (java.text.ParseException)2 SignatureAlgorithm (org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm)2 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)2 Jwt (org.gluu.oxauth.model.jwt.Jwt)2 JSONException (org.json.JSONException)2 JSONObject (org.json.JSONObject)2 PrivateKey (java.security.PrivateKey)1 PublicKey (java.security.PublicKey)1 Signature (java.security.Signature)1 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)1 ArrayList (java.util.ArrayList)1 Response (javax.ws.rs.core.Response)1 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)1