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);
}
}
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);
}
}
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();
}
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;
}
}
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;
}
}
Aggregations