use of com.nimbusds.jwt.JWTClaimsSet in project ovirt-engine by oVirt.
the class OpenIdUtils method createJWTClaimSet.
private static JWTClaimsSet createJWTClaimSet(HttpServletRequest request, SsoSession ssoSession, String clientId) {
String serverName = request.getServerName();
String issuer = String.format("%s://%s:%s", request.getScheme(), InetAddressUtils.isIPv6Address(serverName) ? String.format("[%s]", serverName) : serverName, request.getServerPort());
Date expirationTime = new Date(ssoSession.getAuthTime().getTime() + 30000 * 60);
// Compose the JWT claims set
JWTClaimsSet.Builder jwtClaimsBuilder = new JWTClaimsSet.Builder().jwtID(ssoSession.getPrincipalRecord().get(Authz.PrincipalRecord.ID)).issueTime(ssoSession.getAuthTime()).expirationTime(expirationTime).issuer(issuer).subject(String.format("%s@%s", ssoSession.getUserId(), ssoSession.getProfile())).audience(clientId).claim("acr", "0").claim("auth_time", ssoSession.getAuthTime()).claim("sub", String.format("%s@%s", ssoSession.getUserId(), ssoSession.getProfile())).claim("preferred_username", String.format("%s@%s", ssoSession.getUserId(), ssoSession.getProfile())).claim("email", ssoSession.getPrincipalRecord().<String>get(Authz.PrincipalRecord.EMAIL)).claim("name", ssoSession.getPrincipalRecord().<String>get(Authz.PrincipalRecord.FIRST_NAME)).claim("family_name", ssoSession.getPrincipalRecord().<String>get(Authz.PrincipalRecord.FIRST_NAME)).claim("given_name", ssoSession.getPrincipalRecord().<String>get(Authz.PrincipalRecord.FIRST_NAME));
if (StringUtils.isNotEmpty(ssoSession.getOpenIdNonce())) {
jwtClaimsBuilder.claim("nonce", ssoSession.getOpenIdNonce());
}
return jwtClaimsBuilder.build();
}
use of com.nimbusds.jwt.JWTClaimsSet 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.jwt.JWTClaimsSet in project spring-security by spring-projects.
the class NimbusJwtDecoderTests method decodeWhenUsingSecertKeyWithKidThenStillUsesKey.
// gh-7056
@Test
public void decodeWhenUsingSecertKeyWithKidThenStillUsesKey() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256).keyID("one").build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
// @formatter:on
SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256).build();
assertThat(decoder.decode(signedJwt.serialize())).extracting(Jwt::getSubject).isEqualTo("test-subject");
// @formatter:on
}
use of com.nimbusds.jwt.JWTClaimsSet in project spring-security by spring-projects.
the class NimbusJwtDecoderTests method decodeWhenUsingPublicKeyWithKidThenStillUsesKey.
// gh-7049
@Test
public void decodeWhenUsingPublicKeyWithKidThenStillUsesKey() throws Exception {
RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY;
RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY;
// @formatter:off
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
// @formatter:on
SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey).signatureAlgorithm(SignatureAlgorithm.RS256).build();
assertThat(decoder.decode(signedJwt.serialize())).extracting(Jwt::getSubject).isEqualTo("test-subject");
// @formatter:on
}
use of com.nimbusds.jwt.JWTClaimsSet in project spring-security by spring-projects.
the class NimbusReactiveJwtDecoderTests method decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException.
@Test
public void decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
// @formatter:off
this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build();
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block());
// @formatter:on
}
Aggregations