private void configureSigningParametersForEncoding() { val result = findRsaJsonWebKeyByProvidedKeyId(webKeySet.getJsonWebKeys()); if (result.isEmpty()) { throw new IllegalArgumentException("Could not locate RSA JSON web key from keystore"); } val key = result.get(); if (key.getPrivateKey() == null) { throw new IllegalArgumentException("Private key located from keystore for key id " + key.getKeyId() + " is undefined"); } setSigningKey(key.getPrivateKey()); }
public AuthApplication() { try { RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048); rsaJsonWebKey.setKeyId("k1"); } catch (JoseException e) { throw new HobsonRuntimeException("Error creating RSA web key", e); } }
public static JsonWebKey newJwk(Key key) throws JoseException { if (RSAPublicKey.class.isInstance(key)) { return new RsaJsonWebKey((RSAPublicKey)key); } else if (ECPublicKey.class.isInstance(key)) { return new EllipticCurveJsonWebKey((ECPublicKey)key); } else if (PublicKey.class.isInstance(key)) { throw new JoseException("Unsupported or unknown public key " + key); } else { return new OctetSequenceJsonWebKey(key); } }
BigInteger modulus = getBigIntFromBase64UrlEncodedParam(params, MODULUS_MEMBER_NAME, true); BigInteger publicExponent = getBigIntFromBase64UrlEncodedParam(params, EXPONENT_MEMBER_NAME, true); checkForBareKeyCertMismatch(); BigInteger d = getBigIntFromBase64UrlEncodedParam(params, PRIVATE_EXPONENT_MEMBER_NAME, false); BigInteger p = getBigIntFromBase64UrlEncodedParam(params, FIRST_PRIME_FACTOR_MEMBER_NAME, false); BigInteger q = getBigIntFromBase64UrlEncodedParam(params, SECOND_PRIME_FACTOR_MEMBER_NAME, false); BigInteger dp = getBigIntFromBase64UrlEncodedParam(params, FIRST_FACTOR_CRT_EXPONENT_MEMBER_NAME, false); BigInteger dq = getBigIntFromBase64UrlEncodedParam(params, SECOND_FACTOR_CRT_EXPONENT_MEMBER_NAME, false); BigInteger qi = getBigIntFromBase64UrlEncodedParam(params, FIRST_CRT_COEFFICIENT_MEMBER_NAME, false); privateKey = rsaKeyUtil.privateKey(modulus, publicExponent, d, p, q, dp, dq, qi); removeFromOtherParams(MODULUS_MEMBER_NAME, EXPONENT_MEMBER_NAME, PRIVATE_EXPONENT_MEMBER_NAME,
private void configureSigningParametersForDecoding() { val result = findRsaJsonWebKeyByProvidedKeyId(webKeySet.getJsonWebKeys()); if (result.isEmpty()) { throw new IllegalArgumentException("Could not locate RSA JSON web key from keystore"); } val key = result.get(); if (key.getPublicKey() == null) { throw new IllegalArgumentException("Public key located from keystore for key id " + key.getKeyId() + " is undefined"); } setSigningKey(key.getPublicKey()); }
rsaJsonWebKey.setKeyId("k1"); oidcConfig = new OIDCConfig("Hobson", "/login", "/token", "/userInfo", ".well-known/jwks.json", rsaJsonWebKey); .setRequireSubject() .setExpectedIssuer(oidcConfig.getIssuer()) .setVerificationKey(((RsaJsonWebKey)oidcConfig.getSigningKey()).getKey()) .setExpectedAudience(System.getenv("OIDC_AUDIENCE") != null ? System.getenv("OIDC_AUDIENCE") : System.getProperty("OIDC_AUDIENCE", "hobson-webconsole")) .build();
@Override public String createToken(HobsonUser user) { try { JwtClaims claims = new JwtClaims(); claims.setIssuer(oidcConfig.getIssuer()); claims.setAudience(System.getenv("OIDC_AUDIENCE") != null ? System.getenv("OIDC_AUDIENCE") : System.getProperty("OIDC_AUDIENCE", "hobson-webconsole")); claims.setSubject(user.getId()); claims.setStringClaim(PROP_FIRST_NAME, user.getGivenName()); claims.setStringClaim(PROP_LAST_NAME, user.getFamilyName()); claims.setExpirationTimeMinutesInTheFuture(DEFAULT_EXPIRATION_MINUTES); claims.setClaim("realm_access", Collections.singletonMap("roles", user.getRoles())); Collection<String> hubs = getHubsForUser(user.getId()); if (hubs != null) { claims.setStringClaim("hubs", StringUtils.join(hubs, ",")); } JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(((RsaJsonWebKey)oidcConfig.getSigningKey()).getPrivateKey()); jws.setKeyIdHeaderValue(((RsaJsonWebKey)oidcConfig.getSigningKey()).getKeyType()); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); return jws.getCompactSerialization(); } catch (JoseException e) { logger.error("Error generating token", e); throw new HobsonAuthenticationException("Error generating token"); } }
public static boolean validateToken(String token) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setExpectedIssuer(ISSUER) // whom the JWT needs to have been issued by .setExpectedAudience(AUDIENCE) // to whom the JWT is intended for .setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key .build(); // create the JwtConsumer instance try { // Validate the JWT and process it to the Claims JwtClaims jwtClaims = jwtConsumer.processToClaims(token); //过期时间 //用户名和ID return true; } catch (InvalidJwtException e) { // InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway. // Hopefully with meaningful explanations(s) about what went wrong. System.out.println("Invalid JWT! " + e); return false; } catch (Exception ex) { ex.printStackTrace(); return false; } }
@Override protected String produceThumbprintHashInput() { String template = "{\"e\":\"%s\",\"kty\":\"RSA\",\"n\":\"%s\"}"; HashMap<String, Object> params = new HashMap<>(); fillPublicTypeSpecificParams(params); return String.format(template, params.get(EXPONENT_MEMBER_NAME), params.get(MODULUS_MEMBER_NAME)); } }
private void configureEncryptionParametersForEncoding() { if (httpsJkws.isEmpty()) { LOGGER.debug("No JWKS endpoint is defined. Configuration of encryption parameters and keys are skipped"); } else { try { val keys = this.httpsJkws.get().getJsonWebKeys(); val encKeyResult = findRsaJsonWebKey(keys, Predicates.alwaysTrue()); if (encKeyResult.isEmpty()) { throw new IllegalArgumentException("Could not locate RSA JSON web key from endpoint"); } val encKey = encKeyResult.get(); if (encKey.getPublicKey() == null) { throw new IllegalArgumentException("Public key located from endpoint for key id " + encKey.getKeyId() + " is undefined"); } setSecretKeyEncryptionKey(encKey.getPublicKey()); setContentEncryptionAlgorithmIdentifier(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256); setEncryptionAlgorithm(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
.setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key
private void configureEncryptionParametersForDecoding() { if (httpsJkws.isEmpty()) { LOGGER.debug("No JWKS endpoint is defined. Configuration of encryption parameters and keys are skipped"); } else { try { val keys = this.httpsJkws.get().getJsonWebKeys(); val encKeyResult = findRsaJsonWebKey(keys, Predicates.alwaysTrue()); if (encKeyResult.isEmpty()) { throw new IllegalArgumentException("Could not locate RSA JSON web key from endpoint"); } val encKey = encKeyResult.get(); if (encKey.getPrivateKey() == null) { throw new IllegalArgumentException("Private key located from endpoint for key id " + encKey.getKeyId() + " is undefined"); } setSecretKeyEncryptionKey(encKey.getPrivateKey()); setContentEncryptionAlgorithmIdentifier(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256); setEncryptionAlgorithm(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
public static void generate() throws Exception { RsaJsonWebKey key = RsaJwkGenerator.generateJwk(2048); key.setKeyId("k" + System.currentTimeMillis()); System.out.println("Public & Private:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)); System.out.println(); System.out.println("Only Public:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY)); } }
public static PublicJsonWebKey newPublicJwk(Map<String,Object> params, String jcaProvider) throws JoseException { String kty = getStringRequired(params, KEY_TYPE_PARAMETER); switch (kty) { case RsaJsonWebKey.KEY_TYPE: return new RsaJsonWebKey(params, jcaProvider); case EllipticCurveJsonWebKey.KEY_TYPE: return new EllipticCurveJsonWebKey(params, jcaProvider); default: throw new JoseException("Unknown key type (for public keys): '" + kty + "'"); } }
jws.setKey(rsaJsonWebKey.getPrivateKey()); jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
public static JsonWebKey newJwk(Map<String,Object> params) throws JoseException { String kty = getStringRequired(params, KEY_TYPE_PARAMETER); switch (kty) { case RsaJsonWebKey.KEY_TYPE: return new RsaJsonWebKey(params); case EllipticCurveJsonWebKey.KEY_TYPE: return new EllipticCurveJsonWebKey(params); case OctetSequenceJsonWebKey.KEY_TYPE: return new OctetSequenceJsonWebKey(params); default: throw new JoseException("Unknown key type algorithm: '" + kty + "'"); } }