Search in sources :

Example 16 with JWK

use of com.nimbusds.jose.jwk.JWK in project dhis2-core by dhis2.

the class JwtUtils method selectJwk.

private JWK selectJwk(JoseHeader headers) {
    JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(headers.getJwsAlgorithm().getName());
    JWSHeader jwsHeader = new JWSHeader(jwsAlgorithm);
    JWKSelector jwkSelector = new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
    List<JWK> jwks;
    try {
        jwks = this.jwkSource.get(jwkSelector, null);
    } catch (KeySourceException ex) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key -> " + ex.getMessage()), ex);
    }
    if (jwks.size() > 1) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Found multiple JWK signing keys for algorithm '" + jwsAlgorithm.getName() + "'"));
    }
    return !jwks.isEmpty() ? jwks.get(0) : null;
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWSHeader(com.nimbusds.jose.JWSHeader) KeySourceException(com.nimbusds.jose.KeySourceException) JWK(com.nimbusds.jose.jwk.JWK)

Example 17 with JWK

use of com.nimbusds.jose.jwk.JWK in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method createEmptyJWTwithPublicKey.

/**
 * creates an empty JSON Web Token
 *
 * @param webAppBaseURL - the base url of the application
 *
 * @return the JSON WebToken
 */
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).issueTime(Date.from(currentTime.toInstant())).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        LOGGER.error(e);
    }
    return signedJWT;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 18 with JWK

use of com.nimbusds.jose.jwk.JWK in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method retrievePublicKeyFromAuthenticationToken.

/**
 * retrieves the client public key from Authentication Token
 *
 * @param signedJWT - the authentication token
 * @return the public key as JWK object
 */
public static JWK retrievePublicKeyFromAuthenticationToken(SignedJWT signedJWT) {
    JWK result = null;
    try {
        result = JWK.parse(signedJWT.getJWTClaimsSet().getJSONObjectClaim("sub_jwk"));
        RSAKey publicKey = (RSAKey) signedJWT.getHeader().getJWK();
        if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
            return result;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return null;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JWK(com.nimbusds.jose.jwk.JWK)

Example 19 with JWK

use of com.nimbusds.jose.jwk.JWK in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method createJWT.

/**
 * creates a JSON Web Token with user id, roles and client public key
 *
 * @param user - the user that should be returned
 * @param roles - the roles that should be returned
 * @param webAppBaseURL - the base url of the application
 * @param clientPublicKey -  the client public key as JSON Web Key
 *
 * @return the JSON WebToken
 */
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).issueTime(Date.from(currentTime.toInstant())).notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user).claim("roles", roles).claim("sub_jwk", clientPublicKey).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        // TODO Auto-generated catch block
        LOGGER.error(e);
    }
    System.out.println("JWT: " + signedJWT.serialize());
    return signedJWT;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 20 with JWK

use of com.nimbusds.jose.jwk.JWK in project ddf by codice.

the class OidcTokenValidatorTest method setup.

@Before
public void setup() throws Exception {
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
    when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
    when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
    Resource resource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
    when(configuration.getClientId()).thenReturn("ddf-client");
    when(configuration.getSecret()).thenReturn("secret");
    when(configuration.isUseNonce()).thenReturn(true);
    when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
    when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    when(oidcClient.getNonceSessionAttributeName()).thenReturn(NONCE_SESSION_ATTRIBUTE);
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) Resource(com.nimbusds.jose.util.Resource) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) URI(java.net.URI) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

Aggregations

JWK (com.nimbusds.jose.jwk.JWK)44 Test (org.junit.jupiter.api.Test)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)17 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)17 StandardCharsets (java.nio.charset.StandardCharsets)16 Function (java.util.function.Function)16 SecretKeySpec (javax.crypto.spec.SecretKeySpec)16 MockResponse (okhttp3.mockwebserver.MockResponse)16 MockWebServer (okhttp3.mockwebserver.MockWebServer)16 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)16 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)16 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)16 AfterEach (org.junit.jupiter.api.AfterEach)16 BeforeEach (org.junit.jupiter.api.BeforeEach)16 HttpHeaders (org.springframework.http.HttpHeaders)16 MediaType (org.springframework.http.MediaType)16 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)16 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)16 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)16