use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.
the class AbstractCryptoProvider method processKey.
private PublicKey processKey(Algorithm requestedAlgorithm, String alias, JSONObject key) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException, InvalidParameterException {
PublicKey publicKey = null;
AlgorithmFamily algorithmFamily = null;
if (key.has(JWKParameter.ALGORITHM)) {
Algorithm algorithm = Algorithm.fromString(key.optString(JWKParameter.ALGORITHM));
if (requestedAlgorithm != null && !requestedAlgorithm.equals(algorithm)) {
LOG.trace("kid matched but algorithm does not match. kid algorithm:" + algorithm + ", requestedAlgorithm:" + requestedAlgorithm + ", kid:" + alias);
return null;
}
algorithmFamily = algorithm.getFamily();
} else if (key.has(JWKParameter.KEY_TYPE)) {
algorithmFamily = AlgorithmFamily.fromString(key.getString(JWKParameter.KEY_TYPE));
} else {
throw new InvalidParameterException("Wrong key (JSONObject): doesn't contain 'alg' and 'kty' properties");
}
switch(algorithmFamily) {
case RSA:
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.EXPONENT))));
publicKey = keyFactory.generatePublic(pubKeySpec);
break;
}
case EC:
{
EllipticEdvardsCurve curve = EllipticEdvardsCurve.fromString(key.optString(JWKParameter.CURVE));
AlgorithmParameters parameters = AlgorithmParameters.getInstance(AlgorithmFamily.EC.toString());
parameters.init(new ECGenParameterSpec(curve.getAlias()));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
publicKey = KeyFactory.getInstance(AlgorithmFamily.EC.toString()).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.Y)))), ecParameters));
break;
}
case ED:
{
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64Util.base64urldecode(key.getString(JWKParameter.X)));
publicKey = KeyFactory.getInstance(key.optString(JWKParameter.ALGORITHM)).generatePublic(publicKeySpec);
break;
}
default:
{
throw new InvalidParameterException(String.format("Wrong AlgorithmFamily value: %s", algorithmFamily));
}
}
if (key.has(JWKParameter.EXPIRATION_TIME)) {
checkKeyExpiration(alias, key.getLong(JWKParameter.EXPIRATION_TIME));
}
return publicKey;
}
use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.
the class AbstractCryptoProvider method generateJwks.
public static JSONObject generateJwks(AbstractCryptoProvider cryptoProvider, AppConfiguration configuration) {
GregorianCalendar expirationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
expirationTime.add(Calendar.HOUR, configuration.getKeyRegenerationInterval());
expirationTime.add(Calendar.SECOND, configuration.getIdTokenLifetime());
long expiration = expirationTime.getTimeInMillis();
final List<String> allowedAlgs = configuration.getKeyAlgsAllowedForGeneration();
JSONArray keys = new JSONArray();
for (Algorithm alg : Algorithm.values()) {
try {
final boolean isNotAllowed = !allowedAlgs.isEmpty() && !allowedAlgs.contains(alg.getParamName());
final boolean isNotSupported = !alg.canGenerateKeys();
if (isNotAllowed || isNotSupported) {
if (isNotAllowed) {
LOG.debug(String.format("Key generation for %s is skipped because it's not allowed by keyAlgsAllowedForGeneration configuration property.", alg.toString()));
}
if (isNotSupported) {
LOG.trace(alg + " does not support keys re-generation.");
}
continue;
}
keys.put(cryptoProvider.generateKey(alg, expiration));
} catch (Exception ex) {
LOG.error(String.format("Algorithm: %s", alg), ex);
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put(JWKParameter.JSON_WEB_KEY_SET, keys);
return jsonObject;
}
use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.
the class GetTokensByCodeOperation method execute.
@Override
public IOpResponse execute(GetTokensByCodeParams params) throws Exception {
validate(params);
final Rp rp = getRp();
OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);
final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
tokenRequest.setCode(params.getCode());
tokenRequest.setRedirectUri(rp.getRedirectUri());
tokenRequest.setAuthUsername(rp.getClientId());
AuthenticationMethod authenticationMethod = Strings.isNullOrEmpty(params.getAuthenticationMethod()) ? AuthenticationMethod.fromString(rp.getTokenEndpointAuthMethod()) : AuthenticationMethod.fromString(params.getAuthenticationMethod());
if (authenticationMethod == null) {
LOG.debug("TokenEndpointAuthMethod is either not set or not valid. Setting `client_secret_basic` as AuthenticationMethod. TokenEndpointAuthMethod : {} ", rp.getTokenEndpointAuthMethod());
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
} else {
tokenRequest.setAuthenticationMethod(authenticationMethod);
}
if (Lists.newArrayList(AuthenticationMethod.PRIVATE_KEY_JWT, AuthenticationMethod.TLS_CLIENT_AUTH, AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH).contains(authenticationMethod)) {
Algorithm algorithm = Strings.isNullOrEmpty(params.getAlgorithm()) ? Algorithm.fromString(rp.getTokenEndpointAuthSigningAlg()) : Algorithm.fromString(params.getAlgorithm());
if (algorithm == null) {
LOG.error("TokenEndpointAuthSigningAlg is either not set or not valid. TokenEndpointAuthSigningAlg : {} ", rp.getTokenEndpointAuthSigningAlg());
throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
}
tokenRequest.setAlgorithm(SignatureAlgorithm.fromString(rp.getTokenEndpointAuthSigningAlg()));
if (!getConfigurationService().getConfiguration().getEnableJwksGeneration()) {
LOG.error("The Token Authentication Method is {}. Please set `enable_jwks_generation` (to `true`), `crypt_provider_key_store_path` and `crypt_provider_key_store_password` in `client-api-server.yml` to enable RP-jwks generation in jans-client-api.", authenticationMethod.toString());
throw new HttpException(ErrorResponseCode.JWKS_GENERATION_DISABLE);
}
tokenRequest.setCryptoProvider(getKeyGeneratorService().getCryptoProvider());
tokenRequest.setKeyId(getKeyGeneratorService().getCryptoProvider().getKeyId(getKeyGeneratorService().getKeys(), algorithm, Use.SIGNATURE));
tokenRequest.setAudience(discoveryResponse.getTokenEndpoint());
} else {
tokenRequest.setAuthPassword(rp.getClientSecret());
}
final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
tokenClient.setExecutor(getHttpService().getClientEngine());
tokenClient.setRequest(tokenRequest);
final TokenResponse response = tokenClient.exec();
if (response.getStatus() == 200 || response.getStatus() == 302) {
if (Strings.isNullOrEmpty(response.getIdToken())) {
LOG.error("id_token is not returned. Please check: 1) OP log file for error (oxauth.log) 2) whether 'openid' scope is present for 'get_authorization_url' command");
LOG.error("Entity: " + response.getEntity());
throw new HttpException(ErrorResponseCode.NO_ID_TOKEN_RETURNED);
}
if (Strings.isNullOrEmpty(response.getAccessToken())) {
LOG.error("access_token is not returned");
throw new HttpException(ErrorResponseCode.NO_ACCESS_TOKEN_RETURNED);
}
final Jwt idToken = Jwt.parse(response.getIdToken());
final Validator validator = new Validator.Builder().discoveryResponse(discoveryResponse).idToken(idToken).keyService(getKeyService()).opClientFactory(getOpClientFactory()).rpServerConfiguration(getConfigurationService().getConfiguration()).rp(rp).build();
String state = getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE);
validator.validateNonce(getStateService());
validator.validateIdToken();
validator.validateAccessToken(response.getAccessToken());
validator.validateState(state);
// persist tokens
rp.setIdToken(response.getIdToken());
rp.setAccessToken(response.getAccessToken());
getRpService().update(rp);
getStateService().deleteExpiredObjectsByKey(state);
LOG.trace("Scope: " + response.getScope());
final GetTokensByCodeResponse opResponse = new GetTokensByCodeResponse();
opResponse.setAccessToken(response.getAccessToken());
opResponse.setIdToken(response.getIdToken());
opResponse.setRefreshToken(response.getRefreshToken());
opResponse.setExpiresIn(response.getExpiresIn() != null ? response.getExpiresIn() : -1);
opResponse.setIdTokenClaims(Jackson2.createJsonMapper().readTree(idToken.getClaims().toJsonString()));
return opResponse;
} else {
if (response.getStatus() == 400) {
throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_CODE);
}
LOG.error("Failed to get tokens because response code is: " + response.getScope());
}
return null;
}
use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.
the class KeyGeneratorService method generateKeys.
private JSONWebKeySet generateKeys(List<Algorithm> signatureAlgorithms, List<Algorithm> encryptionAlgorithms, int expiration_hours) {
LOG.trace("Generating jwks keys...");
JSONWebKeySet jwks = new JSONWebKeySet();
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, expiration_hours);
for (Algorithm algorithm : signatureAlgorithms) {
try {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm.name());
JSONObject result = this.cryptoProvider.generateKey(algorithm, calendar.getTimeInMillis());
JSONWebKey key = JSONWebKey.fromJSONObject(result);
jwks.getKeys().add(key);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
for (Algorithm algorithm : encryptionAlgorithms) {
try {
KeyEncryptionAlgorithm encryptionAlgorithm = KeyEncryptionAlgorithm.fromName(algorithm.getParamName());
JSONObject result = this.cryptoProvider.generateKey(algorithm, calendar.getTimeInMillis());
JSONWebKey key = JSONWebKey.fromJSONObject(result);
jwks.getKeys().add(key);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
// LOG.trace("jwks: ", jwks);
LOG.trace("jwks generated successfully.");
return jwks;
}
use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.
the class KeyGeneratorService method generateKeys.
public void generateKeys() {
List<Algorithm> signatureAlgorithms = Lists.newArrayList(Algorithm.RS256, Algorithm.RS384, Algorithm.RS512, Algorithm.ES256, Algorithm.ES384, Algorithm.ES512, Algorithm.PS256, Algorithm.PS384, Algorithm.PS512);
List<Algorithm> encryptionAlgorithms = Lists.newArrayList(Algorithm.RSA1_5, Algorithm.RSA_OAEP);
try {
if (configuration.getEnableJwksGeneration()) {
JSONWebKeySet keySet = generateKeys(signatureAlgorithms, encryptionAlgorithms, configuration.getJwksExpirationInHours());
saveKeysInStorage(keySet.toString());
setKeys(keySet);
}
} catch (Exception e) {
LOG.error("Failed to generate json web keys.", e);
throw new RuntimeException("Failed to generate json web keys.", e);
}
}
Aggregations