use of org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm in project oxAuth by GluuFederation.
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());
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);
// 500
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} finally {
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
}
use of org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm in project oxAuth by GluuFederation.
the class CrossEncryptionTest method nestedJWTProducedByGluu.
@Test
public void nestedJWTProducedByGluu() throws Exception {
AppConfiguration appConfiguration = new AppConfiguration();
List<JSONWebKey> keyArrayList = new ArrayList<JSONWebKey>();
keyArrayList.add(getSenderWebKey());
JSONWebKeySet keySet = new JSONWebKeySet();
keySet.setKeys(keyArrayList);
final JwtSigner jwtSigner = new JwtSigner(appConfiguration, keySet, SignatureAlgorithm.RS256, "audience", null, new AbstractCryptoProvider() {
@Override
public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use) throws Exception {
return null;
}
@Override
public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use, int keyLength) throws Exception {
return null;
}
@Override
public boolean containsKey(String keyId) {
return false;
}
@Override
public String sign(String signingInput, String keyId, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
RSAPrivateKey privateKey = ((RSAKey) JWK.parse(senderJwkJson)).toRSAPrivateKey();
Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
signature.initSign(privateKey);
signature.update(signingInput.getBytes());
return Base64Util.base64urlencode(signature.sign());
}
@Override
public boolean verifySignature(String signingInput, String encodedSignature, String keyId, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
return false;
}
@Override
public boolean deleteKey(String keyId) throws Exception {
return false;
}
@Override
public PrivateKey getPrivateKey(String keyId) throws Exception {
throw new UnsupportedOperationException("Method not implemented.");
}
});
Jwt jwt = jwtSigner.newJwt();
jwt.getClaims().setSubjectIdentifier("testing");
jwt.getClaims().setIssuer("https:devgluu.saminet.local");
jwt = jwtSigner.sign();
RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
Jwe jwe = new Jwe();
jwe.getHeader().setType(JwtType.JWT);
jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
jwe.getHeader().setKeyId("1");
jwe.setSignedJWTPayload(jwt);
JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
String jweString = encrypter.encrypt(jwe).toString();
decryptAndValidateSignatureWithGluu(jweString);
decryptAndValidateSignatureWithNimbus(jweString);
}
use of org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm in project oxAuth by GluuFederation.
the class JweDecrypterImpl method decrypt.
@Override
public Jwe decrypt(String encryptedJwe) throws InvalidJweException {
try {
String[] jweParts = encryptedJwe.split("\\.");
if (jweParts.length != 5) {
throw new InvalidJwtException("Invalid JWS format.");
}
String encodedHeader = jweParts[0];
String encodedEncryptedKey = jweParts[1];
String encodedInitializationVector = jweParts[2];
String encodedCipherText = jweParts[3];
String encodedIntegrityValue = jweParts[4];
Jwe jwe = new Jwe();
jwe.setEncodedHeader(encodedHeader);
jwe.setEncodedEncryptedKey(encodedEncryptedKey);
jwe.setEncodedInitializationVector(encodedInitializationVector);
jwe.setEncodedCiphertext(encodedCipherText);
jwe.setEncodedIntegrityValue(encodedIntegrityValue);
jwe.setHeader(new JwtHeader(encodedHeader));
EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptedJwe);
setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM)));
setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD)));
final KeyEncryptionAlgorithm keyEncryptionAlgorithm = getKeyEncryptionAlgorithm();
Key encriptionKey = null;
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5 || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP) {
encriptionKey = privateKey;
} else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
if (sharedSymmetricKey == null) {
throw new InvalidJweException("The shared symmetric key is null");
}
int keyLength = 16;
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
keyLength = 32;
}
if (sharedSymmetricKey.length != keyLength) {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sharedSymmetricKey = sha.digest(sharedSymmetricKey);
sharedSymmetricKey = Arrays.copyOf(sharedSymmetricKey, keyLength);
}
encriptionKey = new SecretKeySpec(sharedSymmetricKey, 0, sharedSymmetricKey.length, "AES");
} else {
throw new InvalidJweException("The key encryption algorithm is not supported");
}
JWEDecrypter decrypter = DECRYPTER_FACTORY.createJWEDecrypter(encryptedJwt.getHeader(), encriptionKey);
decrypter.getJCAContext().setProvider(SecurityProviderUtility.getInstance());
encryptedJwt.decrypt(decrypter);
final SignedJWT signedJWT = encryptedJwt.getPayload().toSignedJWT();
if (signedJWT != null) {
final Jwt jwt = Jwt.parse(signedJWT.serialize());
jwe.setSignedJWTPayload(jwt);
jwe.setClaims(jwt != null ? jwt.getClaims() : null);
} else {
final String base64encodedPayload = encryptedJwt.getPayload().toString();
jwe.setClaims(new JwtClaims(base64encodedPayload));
}
return jwe;
} catch (Exception e) {
throw new InvalidJweException(e);
}
}
use of org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm in project oxAuth by GluuFederation.
the class JwrService method encryptJwe.
private Jwe encryptJwe(Jwe jwe, Client client) throws Exception {
if (appConfiguration.getUseNestedJwtDuringEncryption()) {
JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, client);
Jwt jwt = jwtSigner.newJwt();
jwt.setClaims(jwe.getClaims());
jwe.setSignedJWTPayload(signJwt(jwt, client));
}
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(ALGORITHM));
final BlockEncryptionAlgorithm encryptionMethod = jwe.getHeader().getEncryptionMethod();
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(client.getJwksUri());
String keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), Algorithm.fromString(keyEncryptionAlgorithm.getName()), Use.ENCRYPTION);
PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys, null);
jwe.getHeader().setKeyId(keyId);
if (publicKey == null) {
throw new InvalidJweException("The public key is not valid");
}
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, encryptionMethod, publicKey);
return jweEncrypter.encrypt(jwe);
}
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
byte[] sharedSymmetricKey = clientService.decryptSecret(client.getClientSecret()).getBytes(StandardCharsets.UTF_8);
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, encryptionMethod, sharedSymmetricKey);
return jweEncrypter.encrypt(jwe);
}
throw new IllegalArgumentException("Unsupported encryption algorithm: " + keyEncryptionAlgorithm);
}
use of org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm in project oxAuth by GluuFederation.
the class JwrService method createJwr.
public JsonWebResponse createJwr(Client client) {
try {
if (client.getIdTokenEncryptedResponseAlg() != null && client.getIdTokenEncryptedResponseEnc() != null) {
Jwe jwe = new Jwe();
// Header
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(client.getIdTokenEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(client.getIdTokenEncryptedResponseEnc());
jwe.getHeader().setType(JwtType.JWT);
jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
return jwe;
} else {
JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, client);
return jwtSigner.newJwt();
}
} catch (Exception e) {
log.error("Failed to create logout_token.", e);
return null;
}
}
Aggregations