Search in sources :

Example 1 with JOSEObjectType

use of com.nimbusds.jose.JOSEObjectType in project spring-security by spring-projects.

the class NimbusJwtDecoderTests method withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType.

// gh-8730
@Test
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
    RestOperations restOperations = mock(RestOperations.class);
    given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
    // @formatter:off
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
    assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("An error occurred while attempting to decode the Jwt: " + "Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
Also used : Arrays(java.util.Arrays) EncodedKeySpec(java.security.spec.EncodedKeySpec) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) BeforeAll(org.junit.jupiter.api.BeforeAll) BDDMockito.given(org.mockito.BDDMockito.given) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) ParseException(java.text.ParseException) RestClientException(org.springframework.web.client.RestClientException) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) MediaType(org.springframework.http.MediaType) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Instant(java.time.Instant) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) List(java.util.List) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) JWSSigner(com.nimbusds.jose.JWSSigner) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) SecretKey(javax.crypto.SecretKey) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) Cache(org.springframework.cache.Cache) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Callable(java.util.concurrent.Callable) JWTProcessor(com.nimbusds.jwt.proc.JWTProcessor) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) BadJWTException(com.nimbusds.jwt.proc.BadJWTException) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) MACSigner(com.nimbusds.jose.crypto.MACSigner) Converter(org.springframework.core.convert.converter.Converter) RequestEntity(org.springframework.http.RequestEntity) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RestOperations(org.springframework.web.client.RestOperations) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) DefaultJOSEObjectTypeVerifier(com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test)

Example 2 with JOSEObjectType

use of com.nimbusds.jose.JOSEObjectType in project spring-security by spring-projects.

the class NimbusJwtEncoder method convert.

private static JWSHeader convert(JwsHeader headers) {
    JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(headers.getAlgorithm().getName()));
    if (headers.getJwkSetUrl() != null) {
        builder.jwkURL(convertAsURI(JoseHeaderNames.JKU, headers.getJwkSetUrl()));
    }
    Map<String, Object> jwk = headers.getJwk();
    if (!CollectionUtils.isEmpty(jwk)) {
        try {
            builder.jwk(JWK.parse(jwk));
        } catch (Exception ex) {
            throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
        }
    }
    String keyId = headers.getKeyId();
    if (StringUtils.hasText(keyId)) {
        builder.keyID(keyId);
    }
    if (headers.getX509Url() != null) {
        builder.x509CertURL(convertAsURI(JoseHeaderNames.X5U, headers.getX509Url()));
    }
    List<String> x509CertificateChain = headers.getX509CertificateChain();
    if (!CollectionUtils.isEmpty(x509CertificateChain)) {
        List<Base64> x5cList = new ArrayList<>();
        x509CertificateChain.forEach((x5c) -> x5cList.add(new Base64(x5c)));
        if (!x5cList.isEmpty()) {
            builder.x509CertChain(x5cList);
        }
    }
    String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
    if (StringUtils.hasText(x509SHA1Thumbprint)) {
        builder.x509CertThumbprint(new Base64URL(x509SHA1Thumbprint));
    }
    String x509SHA256Thumbprint = headers.getX509SHA256Thumbprint();
    if (StringUtils.hasText(x509SHA256Thumbprint)) {
        builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
    }
    String type = headers.getType();
    if (StringUtils.hasText(type)) {
        builder.type(new JOSEObjectType(type));
    }
    String contentType = headers.getContentType();
    if (StringUtils.hasText(contentType)) {
        builder.contentType(contentType);
    }
    Set<String> critical = headers.getCritical();
    if (!CollectionUtils.isEmpty(critical)) {
        builder.criticalParams(critical);
    }
    Map<String, Object> customHeaders = new HashMap<>();
    headers.getHeaders().forEach((name, value) -> {
        if (!JWSHeader.getRegisteredParameterNames().contains(name)) {
            customHeaders.put(name, value);
        }
    });
    if (!customHeaders.isEmpty()) {
        builder.customParams(customHeaders);
    }
    return builder.build();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) Base64(com.nimbusds.jose.util.Base64) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) JOSEException(com.nimbusds.jose.JOSEException) Base64URL(com.nimbusds.jose.util.Base64URL) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 3 with JOSEObjectType

use of com.nimbusds.jose.JOSEObjectType in project wildfly by wildfly.

the class TokenUtil method generateJWT.

public static String generateJWT(final String keyLocation, final String principal, final String birthdate, final String... groups) throws Exception {
    PrivateKey privateKey = loadPrivateKey(keyLocation);
    JWSSigner signer = new RSASSASigner(privateKey);
    JsonArrayBuilder groupsBuilder = Json.createArrayBuilder();
    for (String group : groups) {
        groupsBuilder.add(group);
    }
    long currentTime = System.currentTimeMillis() / 1000;
    JsonObjectBuilder claimsBuilder = Json.createObjectBuilder().add("sub", principal).add("upn", principal).add("iss", "quickstart-jwt-issuer").add("aud", "jwt-audience").add("groups", groupsBuilder.build()).add("birthdate", birthdate).add("jti", UUID.randomUUID().toString()).add("iat", currentTime).add("exp", currentTime + 14400);
    JWSObject jwsObject = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("jwt")).keyID("Test Key").build(), new Payload(claimsBuilder.build().toString()));
    jwsObject.sign(signer);
    return jwsObject.serialize();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) PrivateKey(java.security.PrivateKey) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) Payload(com.nimbusds.jose.Payload) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) JWSObject(com.nimbusds.jose.JWSObject) JWSSigner(com.nimbusds.jose.JWSSigner)

Example 4 with JOSEObjectType

use of com.nimbusds.jose.JOSEObjectType in project quickstart by wildfly.

the class TokenUtil method generateJWT.

public static String generateJWT(final String principal, final String birthdate, final String... groups) throws Exception {
    PrivateKey privateKey = loadPrivateKey("private.pem");
    JWSSigner signer = new RSASSASigner(privateKey);
    JsonArrayBuilder groupsBuilder = Json.createArrayBuilder();
    for (String group : groups) {
        groupsBuilder.add(group);
    }
    long currentTime = System.currentTimeMillis() / 1000;
    JsonObjectBuilder claimsBuilder = Json.createObjectBuilder().add("sub", principal).add("upn", principal).add("iss", "quickstart-jwt-issuer").add("aud", "jwt-audience").add("groups", groupsBuilder.build()).add("birthdate", birthdate).add("jti", UUID.randomUUID().toString()).add("iat", currentTime).add("exp", currentTime + 14400);
    JWSObject jwsObject = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("jwt")).keyID("Test Key").build(), new Payload(claimsBuilder.build().toString()));
    jwsObject.sign(signer);
    return jwsObject.serialize();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) PrivateKey(java.security.PrivateKey) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) Payload(com.nimbusds.jose.Payload) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) JWSObject(com.nimbusds.jose.JWSObject) JWSSigner(com.nimbusds.jose.JWSSigner)

Example 5 with JOSEObjectType

use of com.nimbusds.jose.JOSEObjectType in project spring-security by spring-projects.

the class NimbusJwtDecoderTests method withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes.

// gh-8730
@Test
public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception {
    RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY;
    RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY;
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("JWS")).build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet);
    // @formatter:off
    NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey).signatureAlgorithm(SignatureAlgorithm.RS256).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
    // @formatter:on
    assertThat(decoder.decode(signedJwt.serialize()).hasClaim(JwtClaimNames.EXP)).isNotNull();
}
Also used : JOSEObjectType(com.nimbusds.jose.JOSEObjectType) Arrays(java.util.Arrays) EncodedKeySpec(java.security.spec.EncodedKeySpec) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) BeforeAll(org.junit.jupiter.api.BeforeAll) BDDMockito.given(org.mockito.BDDMockito.given) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) ParseException(java.text.ParseException) RestClientException(org.springframework.web.client.RestClientException) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) MediaType(org.springframework.http.MediaType) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Instant(java.time.Instant) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) List(java.util.List) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) JWSSigner(com.nimbusds.jose.JWSSigner) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JOSEObjectType(com.nimbusds.jose.JOSEObjectType) SecretKey(javax.crypto.SecretKey) OAuth2TokenValidatorResult(org.springframework.security.oauth2.core.OAuth2TokenValidatorResult) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) Cache(org.springframework.cache.Cache) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Callable(java.util.concurrent.Callable) JWTProcessor(com.nimbusds.jwt.proc.JWTProcessor) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) BadJWTException(com.nimbusds.jwt.proc.BadJWTException) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) MACSigner(com.nimbusds.jose.crypto.MACSigner) Converter(org.springframework.core.convert.converter.Converter) RequestEntity(org.springframework.http.RequestEntity) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RestOperations(org.springframework.web.client.RestOperations) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) DefaultJOSEObjectTypeVerifier(com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) 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)

Aggregations

JOSEObjectType (com.nimbusds.jose.JOSEObjectType)9 JWSSigner (com.nimbusds.jose.JWSSigner)8 JWSHeader (com.nimbusds.jose.JWSHeader)7 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)5 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)5 DefaultJOSEObjectTypeVerifier (com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier)5 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)5 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)5 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)5 SignedJWT (com.nimbusds.jwt.SignedJWT)5 KeyFactory (java.security.KeyFactory)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 RSAPublicKey (java.security.interfaces.RSAPublicKey)5 EncodedKeySpec (java.security.spec.EncodedKeySpec)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)5 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)5 ParseException (java.text.ParseException)5 Instant (java.time.Instant)5 Base64 (java.util.Base64)5