use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.
the class IdTokenFactory method generateEncryptedIdToken.
public Jwe generateEncryptedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes, boolean includeIdTokenClaims) throws Exception {
Jwe jwe = new Jwe();
// Header
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseEnc());
jwe.getHeader().setType(JwtType.JWT);
jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
// Claims
jwe.getClaims().setIssuer(appConfiguration.getIssuer());
jwe.getClaims().setAudience(authorizationGrant.getClient().getClientId());
int lifeTime = appConfiguration.getIdTokenLifetime();
Calendar calendar = Calendar.getInstance();
Date issuedAt = calendar.getTime();
calendar.add(Calendar.SECOND, lifeTime);
Date expiration = calendar.getTime();
jwe.getClaims().setExpirationTime(expiration);
jwe.getClaims().setIssuedAt(issuedAt);
if (authorizationGrant.getAcrValues() != null) {
jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues());
setAmrClaim(jwe, authorizationGrant.getAcrValues());
}
if (StringUtils.isNotBlank(nonce)) {
jwe.getClaims().setClaim(JwtClaimName.NONCE, nonce);
}
if (authorizationGrant.getAuthenticationTime() != null) {
jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime());
}
if (authorizationCode != null) {
String codeHash = authorizationCode.getHash(null);
jwe.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash);
}
if (accessToken != null) {
String accessTokenHash = accessToken.getHash(null);
jwe.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash);
}
jwe.getClaims().setClaim(JwtClaimName.OX_OPENID_CONNECT_VERSION, appConfiguration.getOxOpenIdConnectVersion());
List<org.xdi.oxauth.model.common.Scope> dynamicScopes = Lists.newArrayList();
if (includeIdTokenClaims) {
for (String scopeName : scopes) {
org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName);
if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) {
dynamicScopes.add(scope);
continue;
}
if (scope != null && scope.getOxAuthClaims() != null) {
for (String claimDn : scope.getOxAuthClaims()) {
GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn);
String claimName = gluuAttribute.getOxAuthClaimName();
String ldapName = gluuAttribute.getName();
String attributeValue;
if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) {
if (ldapName.equals("uid")) {
attributeValue = authorizationGrant.getUser().getUserId();
} else {
attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName());
}
jwe.getClaims().setClaim(claimName, attributeValue);
}
}
}
}
}
if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) {
for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) {
// ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
boolean optional = true;
GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
if (gluuAttribute != null) {
String ldapClaimName = gluuAttribute.getName();
Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional);
if (attribute != null) {
if (attribute instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) attribute;
List<String> values = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
String value = jsonArray.optString(i);
if (value != null) {
values.add(value);
}
}
jwe.getClaims().setClaim(claim.getName(), values);
} else {
String value = (String) attribute;
jwe.getClaims().setClaim(claim.getName(), value);
}
}
}
}
}
// Check for Subject Identifier Type
if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) {
String sectorIdentifierUri;
if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) {
sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri();
} else {
sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0];
}
String userInum = authorizationGrant.getUser().getAttribute("inum");
PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier(userInum, sectorIdentifierUri);
if (pairwiseIdentifier == null) {
pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri);
pairwiseIdentifier.setId(UUID.randomUUID().toString());
pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseIdentifier.getId(), userInum));
pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier);
}
jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId());
} else {
String openidSubAttribute = appConfiguration.getOpenidSubAttribute();
if (openidSubAttribute.equals("uid")) {
jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getUserId());
} else {
jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute));
}
}
if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwe, unmodifiableAuthorizationGrant);
externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
}
// Encryption
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(authorizationGrant.getClient().getJwksUri());
AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
String keyId = cryptoProvider.getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), SignatureAlgorithm.RS256);
PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys);
if (publicKey != null) {
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey);
jwe = jweEncrypter.encrypt(jwe);
} else {
throw new InvalidJweException("The public key is not valid");
}
} else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
try {
byte[] sharedSymmetricKey = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret()).getBytes(Util.UTF8_STRING_ENCODING);
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey);
jwe = jweEncrypter.encrypt(jwe);
} catch (UnsupportedEncodingException e) {
throw new InvalidJweException(e);
} catch (StringEncrypter.EncryptionException e) {
throw new InvalidJweException(e);
} catch (Exception e) {
throw new InvalidJweException(e);
}
}
return jwe;
}
use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.
the class EncodeClaimsInStateParameter method jwtStateAlgRSAOAEPEncA256GCMTest.
@Parameters({ "keyStoreFile", "keyStoreSecret", "dnName", "RS256_keyId", "clientJwksUri" })
@Test
public void jwtStateAlgRSAOAEPEncA256GCMTest(final String keyStoreFile, final String keyStoreSecret, final String dnName, final String keyId, final String clientJwksUri) throws Exception {
showTitle("jwtStateAlgRSAOAEPEncA256GCMTest");
JSONObject jwks = JwtUtil.getJSONWebKeys(clientJwksUri);
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
String rfp = UUID.randomUUID().toString();
String jti = UUID.randomUUID().toString();
JwtState jwtState = new JwtState(KeyEncryptionAlgorithm.RSA_OAEP, BlockEncryptionAlgorithm.A256GCM, cryptoProvider);
jwtState.setKeyId(keyId);
jwtState.setRfp(rfp);
jwtState.setJti(jti);
jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
String encodedState = jwtState.getEncodedJwt(jwks);
assertNotNull(encodedState);
System.out.println("Encrypted JWE State: " + encodedState);
PrivateKey privateKey = cryptoProvider.getPrivateKey(keyId);
Jwe jwe = Jwe.parse(encodedState, privateKey, null);
assertNotNull(jwe.getClaims().getClaimAsString(KID));
assertNotNull(jwe.getClaims().getClaimAsString(RFP));
assertNotNull(jwe.getClaims().getClaimAsString(JTI));
assertNotNull(jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS));
JSONObject addClaims = jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS);
assertEquals(addClaims.getString("first_name"), "Javier");
assertEquals(addClaims.getString("last_name"), "Rojas");
assertEquals(addClaims.getInt("age"), 34);
assertNotNull(addClaims.getJSONArray("more"));
assertEquals(addClaims.getJSONArray("more").length(), 2);
}
use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.
the class EncodeClaimsInStateParameter method encodeClaimsInStateParameterAlgRSA15EncA256CBCPLUSHS512.
@Parameters({ "userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri", "keyStoreFile", "keyStoreSecret", "dnName", "RS256_keyId", "clientJwksUri" })
@Test
public void encodeClaimsInStateParameterAlgRSA15EncA256CBCPLUSHS512(final String userId, final String userSecret, final String redirectUris, final String redirectUri, final String sectorIdentifierUri, final String keyStoreFile, final String keyStoreSecret, final String dnName, final String keyId, final String clientJwksUri) throws Exception {
showTitle("encodeClaimsInStateParameterAlgRSA15EncA256CBCPLUSHS512");
List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
// 1. Register client
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setResponseTypes(responseTypes);
registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
RegisterClient registerClient = new RegisterClient(registrationEndpoint);
registerClient.setRequest(registerRequest);
RegisterResponse registerResponse = registerClient.exec();
showClient(registerClient);
assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
assertNotNull(registerResponse.getClientId());
assertNotNull(registerResponse.getClientSecret());
assertNotNull(registerResponse.getRegistrationAccessToken());
assertNotNull(registerResponse.getClientIdIssuedAt());
assertNotNull(registerResponse.getClientSecretExpiresAt());
String clientId = registerResponse.getClientId();
// 2. Request authorization
JSONObject jwks = JwtUtil.getJSONWebKeys(clientJwksUri);
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
String nonce = UUID.randomUUID().toString();
String rfp = UUID.randomUUID().toString();
String jti = UUID.randomUUID().toString();
JwtState jwtState = new JwtState(KeyEncryptionAlgorithm.RSA1_5, BlockEncryptionAlgorithm.A256CBC_PLUS_HS512, cryptoProvider);
jwtState.setKeyId(keyId);
jwtState.setRfp(rfp);
jwtState.setJti(jti);
jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
String encodedState = jwtState.getEncodedJwt(jwks);
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
authorizationRequest.setState(encodedState);
AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
assertNotNull(authorizationResponse.getLocation(), "The location is null");
assertNotNull(authorizationResponse.getAccessToken(), "The accessToken is null");
assertNotNull(authorizationResponse.getTokenType(), "The tokenType is null");
assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
assertNotNull(authorizationResponse.getState(), "The state is null");
String state = authorizationResponse.getState();
// 3. Decrypt state
PrivateKey privateKey = cryptoProvider.getPrivateKey(keyId);
Jwe jwe = Jwe.parse(state, privateKey, null);
assertNotNull(jwe.getClaims().getClaimAsString(KID));
assertNotNull(jwe.getClaims().getClaimAsString(RFP));
assertNotNull(jwe.getClaims().getClaimAsString(JTI));
assertNotNull(jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS));
JSONObject addClaims = jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS);
assertEquals(addClaims.getString("first_name"), "Javier");
assertEquals(addClaims.getString("last_name"), "Rojas");
assertEquals(addClaims.getInt("age"), 34);
assertNotNull(addClaims.getJSONArray("more"));
assertEquals(addClaims.getJSONArray("more").length(), 2);
}
use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.
the class EncodeClaimsInStateParameter method encodeClaimsInStateParameterAlgRSAOAEPEncA256GCM.
@Parameters({ "userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri", "keyStoreFile", "keyStoreSecret", "dnName", "RS256_keyId", "clientJwksUri" })
@Test
public void encodeClaimsInStateParameterAlgRSAOAEPEncA256GCM(final String userId, final String userSecret, final String redirectUris, final String redirectUri, final String sectorIdentifierUri, final String keyStoreFile, final String keyStoreSecret, final String dnName, final String keyId, final String clientJwksUri) throws Exception {
showTitle("encodeClaimsInStateParameterAlgRSAOAEPEncA256GCM");
List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
// 1. Register client
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setResponseTypes(responseTypes);
registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
RegisterClient registerClient = new RegisterClient(registrationEndpoint);
registerClient.setRequest(registerRequest);
RegisterResponse registerResponse = registerClient.exec();
showClient(registerClient);
assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
assertNotNull(registerResponse.getClientId());
assertNotNull(registerResponse.getClientSecret());
assertNotNull(registerResponse.getRegistrationAccessToken());
assertNotNull(registerResponse.getClientIdIssuedAt());
assertNotNull(registerResponse.getClientSecretExpiresAt());
String clientId = registerResponse.getClientId();
// 2. Request authorization
JSONObject jwks = JwtUtil.getJSONWebKeys(clientJwksUri);
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
String nonce = UUID.randomUUID().toString();
String rfp = UUID.randomUUID().toString();
String jti = UUID.randomUUID().toString();
JwtState jwtState = new JwtState(KeyEncryptionAlgorithm.RSA_OAEP, BlockEncryptionAlgorithm.A256GCM, cryptoProvider);
jwtState.setKeyId(keyId);
jwtState.setRfp(rfp);
jwtState.setJti(jti);
jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
String encodedState = jwtState.getEncodedJwt(jwks);
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
authorizationRequest.setState(encodedState);
AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
assertNotNull(authorizationResponse.getLocation(), "The location is null");
assertNotNull(authorizationResponse.getAccessToken(), "The accessToken is null");
assertNotNull(authorizationResponse.getTokenType(), "The tokenType is null");
assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
assertNotNull(authorizationResponse.getState(), "The state is null");
String state = authorizationResponse.getState();
// 3. Decrypt state
PrivateKey privateKey = cryptoProvider.getPrivateKey(keyId);
Jwe jwe = Jwe.parse(state, privateKey, null);
assertNotNull(jwe.getClaims().getClaimAsString(KID));
assertNotNull(jwe.getClaims().getClaimAsString(RFP));
assertNotNull(jwe.getClaims().getClaimAsString(JTI));
assertNotNull(jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS));
JSONObject addClaims = jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS);
assertEquals(addClaims.getString("first_name"), "Javier");
assertEquals(addClaims.getString("last_name"), "Rojas");
assertEquals(addClaims.getInt("age"), 34);
assertNotNull(addClaims.getJSONArray("more"));
assertEquals(addClaims.getJSONArray("more").length(), 2);
}
use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.
the class EncodeClaimsInStateParameter method jwtStateAlgRSA15EncA256CBCPLUSHS512Test.
@Parameters({ "keyStoreFile", "keyStoreSecret", "dnName", "RS256_keyId", "clientJwksUri" })
@Test
public void jwtStateAlgRSA15EncA256CBCPLUSHS512Test(final String keyStoreFile, final String keyStoreSecret, final String dnName, final String keyId, final String clientJwksUri) throws Exception {
showTitle("jwtStateAlgRSA15EncA256CBCPLUSHS512Test");
JSONObject jwks = JwtUtil.getJSONWebKeys(clientJwksUri);
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
String rfp = UUID.randomUUID().toString();
String jti = UUID.randomUUID().toString();
JwtState jwtState = new JwtState(KeyEncryptionAlgorithm.RSA1_5, BlockEncryptionAlgorithm.A256CBC_PLUS_HS512, cryptoProvider);
jwtState.setKeyId(keyId);
jwtState.setRfp(rfp);
jwtState.setJti(jti);
jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
String encodedState = jwtState.getEncodedJwt(jwks);
assertNotNull(encodedState);
System.out.println("Encrypted JWE State: " + encodedState);
PrivateKey privateKey = cryptoProvider.getPrivateKey(keyId);
Jwe jwe = Jwe.parse(encodedState, privateKey, null);
assertNotNull(jwe.getClaims().getClaimAsString(KID));
assertNotNull(jwe.getClaims().getClaimAsString(RFP));
assertNotNull(jwe.getClaims().getClaimAsString(JTI));
assertNotNull(jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS));
JSONObject addClaims = jwe.getClaims().getClaimAsJSON(ADDITIONAL_CLAIMS);
assertEquals(addClaims.getString("first_name"), "Javier");
assertEquals(addClaims.getString("last_name"), "Rojas");
assertEquals(addClaims.getInt("age"), 34);
assertNotNull(addClaims.getJSONArray("more"));
assertEquals(addClaims.getJSONArray("more").length(), 2);
}
Aggregations