Search in sources :

Example 16 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class AuthorizeRestWebServiceImpl method fillRedirectUriResponseforJARM.

private void fillRedirectUriResponseforJARM(RedirectUriResponse redirectUriResponse, JsonWebResponse jwr, Client client) {
    try {
        if (jwr != null) {
            String tempRedirectUri = jwr.getClaims().getClaimAsString("redirect_uri");
            if (StringUtils.isNotBlank(tempRedirectUri)) {
                redirectUriResponse.getRedirectUri().setBaseRedirectUri(URLDecoder.decode(tempRedirectUri, "UTF-8"));
            }
        }
        String clientId = client.getClientId();
        redirectUriResponse.getRedirectUri().setIssuer(appConfiguration.getIssuer());
        redirectUriResponse.getRedirectUri().setAudience(clientId);
        redirectUriResponse.getRedirectUri().setAuthorizationCodeLifetime(appConfiguration.getAuthorizationCodeLifetime());
        redirectUriResponse.getRedirectUri().setSignatureAlgorithm(SignatureAlgorithm.fromString(client.getAttributes().getAuthorizationSignedResponseAlg()));
        redirectUriResponse.getRedirectUri().setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.fromName(client.getAttributes().getAuthorizationEncryptedResponseAlg()));
        redirectUriResponse.getRedirectUri().setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.fromName(client.getAttributes().getAuthorizationEncryptedResponseEnc()));
        redirectUriResponse.getRedirectUri().setCryptoProvider(cryptoProvider);
        String keyId = null;
        if (client.getAttributes().getAuthorizationEncryptedResponseAlg() != null && client.getAttributes().getAuthorizationEncryptedResponseEnc() != null) {
            if (client.getAttributes().getAuthorizationSignedResponseAlg() != null) {
                // Signed then Encrypted
                // response
                SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(client.getAttributes().getAuthorizationSignedResponseAlg());
                String nestedKeyId = new ServerCryptoProvider(cryptoProvider).getKeyId(webKeysConfiguration, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
                JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(client.getJwksUri());
                redirectUriResponse.getRedirectUri().setNestedJsonWebKeys(jsonWebKeys);
                String clientSecret = clientService.decryptSecret(client.getClientSecret());
                redirectUriResponse.getRedirectUri().setNestedSharedSecret(clientSecret);
                redirectUriResponse.getRedirectUri().setNestedKeyId(nestedKeyId);
            }
            // Encrypted response
            JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(client.getJwksUri());
            if (jsonWebKeys != null) {
                keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), Algorithm.fromString(client.getAttributes().getAuthorizationEncryptedResponseAlg()), Use.ENCRYPTION);
            }
            String sharedSecret = clientService.decryptSecret(client.getClientSecret());
            byte[] sharedSymmetricKey = sharedSecret.getBytes(StandardCharsets.UTF_8);
            redirectUriResponse.getRedirectUri().setSharedSymmetricKey(sharedSymmetricKey);
            redirectUriResponse.getRedirectUri().setJsonWebKeys(jsonWebKeys);
            redirectUriResponse.getRedirectUri().setKeyId(keyId);
        } else {
            // Signed response
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
            if (client.getAttributes().getAuthorizationSignedResponseAlg() != null) {
                signatureAlgorithm = SignatureAlgorithm.fromString(client.getAttributes().getAuthorizationSignedResponseAlg());
            }
            keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(webKeysConfiguration, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
            JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(client.getJwksUri());
            redirectUriResponse.getRedirectUri().setJsonWebKeys(jsonWebKeys);
            String clientSecret = clientService.decryptSecret(client.getClientSecret());
            redirectUriResponse.getRedirectUri().setSharedSecret(clientSecret);
            redirectUriResponse.getRedirectUri().setKeyId(keyId);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Also used : JSONObject(org.json.JSONObject) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) InvalidSessionStateException(io.jans.as.server.model.exception.InvalidSessionStateException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) AcrChangedException(io.jans.as.server.model.exception.AcrChangedException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidRedirectUrlException(io.jans.as.server.model.exception.InvalidRedirectUrlException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException)

Example 17 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

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());
    errorResponseFactory.validateComponentEnabled(ComponentType.USERINFO);
    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(Constants.PRAGMA, Constants.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(io.jans.as.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) User(io.jans.as.common.model.common.User) AbstractToken(io.jans.as.server.model.common.AbstractToken) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) UnmodifiableAuthorizationGrant(io.jans.as.server.model.common.UnmodifiableAuthorizationGrant) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) InvalidClaimException(io.jans.as.model.exception.InvalidClaimException) ParseException(java.text.ParseException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) InvalidJweException(io.jans.as.model.exception.InvalidJweException) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 18 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm 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 19 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class CheckAccessTokenOperation method isAccessTokenValid.

private boolean isAccessTokenValid(String p_accessToken, Jwt jwt, OpenIdConfigurationResponse discoveryResponse) {
    try {
        // final String type = jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final String jwkUrl = discoveryResponse.getJwksUri();
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm);
        final RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwkUrl, kid);
        final RSASigner rsaSigner = new RSASigner(signatureAlgorithm, publicKey);
        return rsaSigner.validateAccessToken(p_accessToken, jwt);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm)

Example 20 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class JwtUtil method validateSignature.

public boolean validateSignature(Jwt jwt, JSONWebKeySet jsonWebKeySet) {
    log.trace("\n\n JwtUtil::validateSignature() - jwt = " + jwt + " , jsonWebKeySet =" + jsonWebKeySet + "\n");
    try {
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
        log.trace("\n\n JwtUtil::validateSignature() - kid = " + kid + " , algorithm =" + algorithm + " signatureAlgorithm = " + signatureAlgorithm + "\n");
        PublicKey publicKey = getPublicKey(kid, jsonWebKeySet, signatureAlgorithm);
        log.trace("\n\n JwtUtil::validateSignature() - publicKey = " + publicKey + "\n");
        if (publicKey == null) {
            log.error("Failed to get RSA public key.");
            return false;
        }
        // Validate
        AbstractJwsSigner signer = null;
        if (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
            signer = new RSASigner(SignatureAlgorithm.fromString(algorithm), (RSAPublicKey) publicKey);
        } else if (AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
            signer = new ECDSASigner(SignatureAlgorithm.fromString(algorithm), (ECDSAPublicKey) publicKey);
        }
        if (signer == null) {
            log.error("ID Token signer is not found!");
            return false;
        }
        boolean signature = signer.validate(jwt);
        if (signature) {
            log.debug("ID Token is successfully validated.");
            return true;
        }
        log.error("ID Token signature invalid.");
        return false;
    } catch (Exception e) {
        log.error("Failed to validate id_token. Message: " + e.getMessage(), e);
        return false;
    }
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) ECDSASigner(io.jans.as.model.jws.ECDSASigner) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey) PublicKey(io.jans.as.model.crypto.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) AbstractJwsSigner(io.jans.as.model.jws.AbstractJwsSigner) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)28 JSONObject (org.json.JSONObject)10 Jwt (io.jans.as.model.jwt.Jwt)8 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)7 HttpException (io.jans.ca.server.HttpException)7 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 Client (io.jans.as.common.model.registration.Client)5 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)5 BlockEncryptionAlgorithm (io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)4 ECDSAPublicKey (io.jans.as.model.crypto.signature.ECDSAPublicKey)4 Signature (java.security.Signature)4 SignatureException (java.security.SignatureException)4 Date (java.util.Date)4 User (io.jans.as.common.model.common.User)3 AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)3 CryptoProviderException (io.jans.as.model.exception.CryptoProviderException)3 ECDSASigner (io.jans.as.model.jws.ECDSASigner)3 RegisterRequest (io.jans.as.client.RegisterRequest)2 GrantType (io.jans.as.model.common.GrantType)2