Java Code Examples for org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm#fromString()

The following examples show how to use org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm#fromString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwkResponse.java    From oxAuth with MIT License 6 votes vote down vote up
@Deprecated
public PublicKey getPublicKey(String keyId) {
    PublicKey publicKey = null;
    JSONWebKey JSONWebKey = getKeyValue(keyId);

    if (JSONWebKey != null) {
        switch (JSONWebKey.getKty()) {
            case RSA:
                publicKey = new RSAPublicKey(
                        JSONWebKey.getN(),
                        JSONWebKey.getE());
                break;
            case EC:
                publicKey = new ECDSAPublicKey(
                        SignatureAlgorithm.fromString(JSONWebKey.getAlg().getParamName()),
                        JSONWebKey.getX(),
                        JSONWebKey.getY());
                break;
            default:
                break;
        }
    }

    return publicKey;
}
 
Example 2
Source File: CheckAccessTokenOperation.java    From oxd with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 3
Source File: JwtSigner.java    From oxAuth with MIT License 5 votes vote down vote up
public static JwtSigner newJwtSigner(AppConfiguration appConfiguration, JSONWebKeySet webKeys, Client client) throws Exception {
    Preconditions.checkNotNull(client);

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getIdTokenSignedResponseAlg() != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getIdTokenSignedResponseAlg());
    }

    ClientService clientService = CdiUtil.bean(ClientService.class);
    return new JwtSigner(appConfiguration, webKeys, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
}
 
Example 4
Source File: AuthorizationGrant.java    From oxAuth with MIT License 5 votes vote down vote up
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());
    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);
    }

    return jwtSigner.sign().toString();
}
 
Example 5
Source File: UmaValidationService.java    From oxAuth with MIT License 5 votes vote down vote up
public boolean isIdTokenValid(Jwt idToken) {
    try {
        final String issuer = idToken.getClaims().getClaimAsString(JwtClaimName.ISSUER);
        //final String nonceFromToken = idToken.getClaims().getClaimAsString(JwtClaimName.NONCE);
        //final String audienceFromToken = idToken.getClaims().getClaimAsString(JwtClaimName.AUDIENCE);

        final Date expiresAt = idToken.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
        final Date now = new Date();
        if (now.after(expiresAt)) {
            log.error("ID Token is expired. (It is after " + now + ").");
            return false;
        }

        // 1. validate issuer
        if (!issuer.equals(appConfiguration.getIssuer())) {
            log.error("ID Token issuer is invalid. Token issuer: " + issuer + ", server issuer: " + appConfiguration.getIssuer());
            return false;
        }

        // 2. validate signature
        final String kid = idToken.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final String algorithm = idToken.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        RSAPublicKey publicKey = getPublicKey(kid);
        if (publicKey != null) {
            RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.fromString(algorithm), publicKey);
            boolean signature = rsaSigner.validate(idToken);
            if (signature) {
                log.debug("ID Token is successfully validated.");
                return true;
            }
            log.error("ID Token signature is invalid.");
        } else {
            log.error("Failed to get RSA public key.");
        }
        return false;
    } catch (Exception e) {
        log.error("Failed to validate id_token. Message: " + e.getMessage(), e);
        return false;
    }
}
 
Example 6
Source File: UmaRptService.java    From oxAuth with MIT License 5 votes vote down vote up
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();
}
 
Example 7
Source File: UserInfoRestWebServiceImpl.java    From oxAuth with MIT License 4 votes vote down vote up
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);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); // 500
        } finally {
            applicationAuditLogger.sendMessage(oAuth2AuditLog);
        }
    }
 
Example 8
Source File: JwtHeader.java    From oxAuth with MIT License 4 votes vote down vote up
public SignatureAlgorithm getSignatureAlgorithm() {
    String alg = getClaimAsString(ALGORITHM);
    return SignatureAlgorithm.fromString(alg);
}
 
Example 9
Source File: OxAuthCryptoProvider.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use) throws Exception {

    KeyPairGenerator keyGen = null;

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm.getParamName());;
    if (signatureAlgorithm == null) {
        signatureAlgorithm = SignatureAlgorithm.RS256;
    }

    if (algorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (AlgorithmFamily.RSA.equals(algorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(algorithm.getFamily().toString(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (AlgorithmFamily.EC.equals(algorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(algorithm.getFamily().toString(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }

    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();

    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;

    String alias = UUID.randomUUID().toString() + getKidSuffix(use, algorithm);
    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);

    final String oldAliasByAlgorithm = getAliasByAlgorithmForDeletion(algorithm, alias, use);
    if (StringUtils.isNotBlank(oldAliasByAlgorithm)) {
        keyStore.deleteEntry(oldAliasByAlgorithm);
        LOG.trace("New key: " + alias + ", deleted key: " + oldAliasByAlgorithm);
    }

    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());

    PublicKey publicKey = keyPair.getPublic();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, algorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, use.getParamName());
    jsonObject.put(ALGORITHM, algorithm.getParamName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve().getName());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);

    return jsonObject;
}
 
Example 10
Source File: JwtUtil.java    From oxAuth with MIT License 4 votes vote down vote up
public static PublicKey getPublicKey(
        String jwksUri, String jwks, SignatureAlgorithm signatureAlgorithm, String keyId) {
    log.debug("Retrieving JWK...");

    JSONObject jsonKeyValue = getJsonKey(jwksUri, jwks, keyId);

    if (jsonKeyValue == null) {
        return null;
    }

    org.gluu.oxauth.model.crypto.PublicKey publicKey = null;

    try {
        String resultKeyId = jsonKeyValue.getString(KEY_ID);
        if (signatureAlgorithm == null) {
            signatureAlgorithm = SignatureAlgorithm.fromString(jsonKeyValue.getString(ALGORITHM));
            if (signatureAlgorithm == null) {
                log.error(String.format("Failed to determine key '%s' signature algorithm", resultKeyId));
                return null;
            }
        }

        JSONObject jsonPublicKey = jsonKeyValue;
        if (jsonKeyValue.has(PUBLIC_KEY)) {
            // Use internal jwks.json format
            jsonPublicKey = jsonKeyValue.getJSONObject(PUBLIC_KEY);
        }

        if (signatureAlgorithm == SignatureAlgorithm.RS256 || signatureAlgorithm == SignatureAlgorithm.RS384 || signatureAlgorithm == SignatureAlgorithm.RS512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            String exp = jsonPublicKey.getString(EXPONENT);
            String mod = jsonPublicKey.getString(MODULUS);

            BigInteger publicExponent = new BigInteger(1, Base64Util.base64urldecode(exp));
            BigInteger modulus = new BigInteger(1, Base64Util.base64urldecode(mod));

            publicKey = new RSAPublicKey(modulus, publicExponent);
        } else if (signatureAlgorithm == SignatureAlgorithm.ES256 || signatureAlgorithm == SignatureAlgorithm.ES384 || signatureAlgorithm == SignatureAlgorithm.ES512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            //String crv = jsonKeyValue.getString(CURVE);
            String xx = jsonPublicKey.getString(X);
            String yy = jsonPublicKey.getString(Y);

            BigInteger x = new BigInteger(1, Base64Util.base64urldecode(xx));
            BigInteger y = new BigInteger(1, Base64Util.base64urldecode(yy));

            publicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);
        }

        if (publicKey != null && jsonKeyValue.has(CERTIFICATE_CHAIN)) {
            final String BEGIN = "-----BEGIN CERTIFICATE-----";
            final String END = "-----END CERTIFICATE-----";

            JSONArray certChain = jsonKeyValue.getJSONArray(CERTIFICATE_CHAIN);
            String certificateString = BEGIN + "\n" + certChain.getString(0) + "\n" + END;
            StringReader sr = new StringReader(certificateString);
            PEMParser pemReader = new PEMParser(sr);
            X509Certificate cert = (X509CertificateObject) pemReader.readObject();
            Certificate certificate = new Certificate(signatureAlgorithm, cert);
            publicKey.setCertificate(certificate);
        }
        if (publicKey != null) {
            publicKey.setKeyId(resultKeyId);
            publicKey.setSignatureAlgorithm(signatureAlgorithm);
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    return publicKey;
}