use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.
the class KnoxServiceTest method testRequiredAudience.
@Test
public void testRequiredAudience() throws Exception {
final String subject = "user-1";
final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair pair = keyGen.generateKeyPair();
final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
final KnoxConfiguration configuration = getConfiguration(publicKey);
when(configuration.getAudiences()).thenReturn(null);
final KnoxService service = new KnoxService(configuration);
Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.
the class KnoxServiceTest method testSignedJwt.
@Test
public void testSignedJwt() throws Exception {
final String subject = "user-1";
final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair pair = keyGen.generateKeyPair();
final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);
final KnoxConfiguration configuration = getConfiguration(publicKey);
final KnoxService service = new KnoxService(configuration);
Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
use of com.nimbusds.oauth2.sdk.id.Subject in project nifi by apache.
the class KnoxServiceTest method testBadSignedJwt.
@Test(expected = InvalidAuthenticationException.class)
public void testBadSignedJwt() throws Exception {
final String subject = "user-1";
final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
final KeyPair pair1 = keyGen.generateKeyPair();
final RSAPrivateKey privateKey1 = (RSAPrivateKey) pair1.getPrivate();
final KeyPair pair2 = keyGen.generateKeyPair();
final RSAPublicKey publicKey2 = (RSAPublicKey) pair2.getPublic();
// sign the jwt with pair 1
final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, AUDIENCE, expiration);
final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey1, null, null);
// attempt to verify it with pair 2
final KnoxConfiguration configuration = getConfiguration(publicKey2);
final KnoxService service = new KnoxService(configuration);
service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize());
}
use of com.nimbusds.oauth2.sdk.id.Subject in project pac4j by pac4j.
the class OidcProfileCreator method create.
@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
init();
final AccessToken accessToken = credentials.getAccessToken();
// Create profile
final U profile = getProfileDefinition().newProfile();
profile.setAccessToken(accessToken);
final JWT idToken = credentials.getIdToken();
profile.setIdTokenString(idToken.getParsedString());
// Check if there is a refresh token
final RefreshToken refreshToken = credentials.getRefreshToken();
if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
profile.setRefreshToken(refreshToken);
logger.debug("Refresh Token successful retrieved");
}
try {
// check idToken
final Nonce nonce;
if (configuration.isUseNonce()) {
nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
} else {
nonce = null;
}
// Check ID Token
final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
assertNotNull("claimsSet", claimsSet);
profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
// User Info request
if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
final HTTPResponse httpResponse = userInfoHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
if (userInfoResponse instanceof UserInfoErrorResponse) {
logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
} else {
final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
final JWTClaimsSet userInfoClaimsSet;
if (userInfoSuccessResponse.getUserInfo() != null) {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
} else {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
}
getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
}
}
// add attributes of the ID token if they don't already exist
for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();
// it's not the subject and this attribute does not already exist, add it
if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
}
}
return profile;
} catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
throw new TechnicalException(e);
}
}
use of com.nimbusds.oauth2.sdk.id.Subject in project pac4j by pac4j.
the class OidcProfileCreator method create.
@Override
@SuppressWarnings("unchecked")
public Optional<UserProfile> create(final Credentials cred, final WebContext context, final SessionStore sessionStore) {
init();
final var credentials = (OidcCredentials) cred;
final var accessToken = credentials.getAccessToken();
// Create profile
final var profile = (OidcProfile) getProfileDefinition().newProfile();
profile.setAccessToken(accessToken);
final var idToken = credentials.getIdToken();
profile.setIdTokenString(idToken.getParsedString());
// Check if there is a refresh token
final var refreshToken = credentials.getRefreshToken();
if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
profile.setRefreshToken(refreshToken);
logger.debug("Refresh Token successful retrieved");
}
try {
final Nonce nonce;
if (configuration.isUseNonce()) {
nonce = new Nonce((String) sessionStore.get(context, client.getNonceSessionAttributeName()).orElse(null));
} else {
nonce = null;
}
// Check ID Token
final var claimsSet = configuration.findTokenValidator().validate(idToken, nonce);
assertNotNull("claimsSet", claimsSet);
profile.setId(ProfileHelper.sanitizeIdentifier(claimsSet.getSubject()));
// User Info request
if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), accessToken);
final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
configuration.configureHttpRequest(userInfoHttpRequest);
final var httpResponse = userInfoHttpRequest.send();
logger.debug("User info response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final var userInfoResponse = UserInfoResponse.parse(httpResponse);
if (userInfoResponse instanceof UserInfoErrorResponse) {
logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
} else {
final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
final JWTClaimsSet userInfoClaimsSet;
if (userInfoSuccessResponse.getUserInfo() != null) {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
} else {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
}
if (userInfoClaimsSet != null) {
getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
} else {
logger.warn("Cannot retrieve claims from user info");
}
}
}
// add attributes of the ID token if they don't already exist
for (final var entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
final var key = entry.getKey();
final var value = entry.getValue();
// it's not the subject and this attribute does not already exist, add it
if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
}
}
// session expiration with token behavior
profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
// keep the session ID if provided
final var sid = (String) claimsSet.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
if (isNotBlank(sid)) {
configuration.findLogoutHandler().recordSession(context, sessionStore, sid);
}
return Optional.of(profile);
} catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
throw new TechnicalException(e);
}
}
Aggregations