Search in sources :

Example 21 with JWTClaimsSet

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();
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Date(java.util.Date)

Example 22 with JWTClaimsSet

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);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 23 with JWTClaimsSet

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
}
Also used : SecretKey(javax.crypto.SecretKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 24 with JWTClaimsSet

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
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 25 with JWTClaimsSet

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
}
Also used : MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) SecretKey(javax.crypto.SecretKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.jupiter.api.Test)

Aggregations

JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)69 SignedJWT (com.nimbusds.jwt.SignedJWT)44 JWSHeader (com.nimbusds.jose.JWSHeader)23 Date (java.util.Date)19 Test (org.junit.Test)16 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)14 Test (org.junit.jupiter.api.Test)11 JOSEException (com.nimbusds.jose.JOSEException)9 ParseException (java.text.ParseException)9 SecretKey (javax.crypto.SecretKey)8 JWSSigner (com.nimbusds.jose.JWSSigner)7 MacAlgorithm (org.springframework.security.oauth2.jose.jws.MacAlgorithm)7 Instant (java.time.Instant)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)6 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)5 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)5 JWT (com.nimbusds.jwt.JWT)5