Search in sources :

Example 6 with Base64URL

use of com.nimbusds.jose.util.Base64URL in project carbon-apimgt by wso2.

the class JWTValidatorImplTest method testValidateToken.

@Test
@PrepareForTest({ CertificateMgtUtils.class, JWTUtil.class, APIManagerConfiguration.class, ServiceReferenceHolder.class, APIManagerConfigurationService.class, APIUtil.class, X509CertUtils.class })
public void testValidateToken() {
    TokenIssuerDto tokenIssuerDto = new TokenIssuerDto("https://localhost:9444/services");
    Mockito.when(signedJWT.getHeader()).thenReturn(jwsHeader);
    PowerMockito.mockStatic(JWTUtil.class);
    byte[] encodedCertificateUnmatched = "aaaaaaaaaaaaaaaa".getBytes();
    try {
        PowerMockito.when(JWTUtil.verifyTokenSignature(signedJWT, KeyId)).thenReturn(true);
    } catch (APIManagementException e) {
        log.info("Exception while signature verification. " + e);
        Assert.fail();
    }
    // Create a mock APIManagerConfiguration Object for retrieving properties from the deployment.toml
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIManagerConfiguration.class);
    PowerMockito.mockStatic(APIManagerConfigurationService.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(CertificateMgtUtils.class);
    PowerMockito.mockStatic(X509CertUtils.class);
    APIManagerConfiguration apiManagerConfiguration = PowerMockito.mock(APIManagerConfiguration.class);
    ServiceReferenceHolder serviceReferenceHolder = PowerMockito.mock(ServiceReferenceHolder.class);
    APIManagerConfigurationService apiManagerConfigurationService = PowerMockito.mock(APIManagerConfigurationService.class);
    OAuthServerConfiguration oAuthServerConfiguration = Mockito.mock(OAuthServerConfiguration.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(oAuthServerConfiguration.getTimeStampSkewInSeconds()).thenReturn(300L);
    Mockito.when(serviceReferenceHolder.getOauthServerConfiguration()).thenReturn(oAuthServerConfiguration);
    JWTValidatorImpl jwtValidator = new JWTValidatorImpl();
    JWKSConfigurationDTO jwksConfigurationDTO = new JWKSConfigurationDTO();
    tokenIssuerDto.setJwksConfigurationDTO(jwksConfigurationDTO);
    jwksConfigurationDTO.setEnabled(false);
    jwtValidator.loadTokenIssuerConfiguration(tokenIssuerDto);
    try {
        JWTValidationInfo validatedInfo = jwtValidator.validateToken(signedJWTInfo);
        assertTrue(validatedInfo.isValid(), "JWT certificate bound access token validation failed even when the" + " configuration is not enabled.");
    } catch (APIManagementException e) {
        Assert.fail();
    }
    // test when certificate is found in the trust store but cnf thumbprint is not matching with the certificate
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    X509Certificate x509Certificate = Mockito.mock(X509Certificate.class);
    java.security.cert.X509Certificate x509CertificateJava = Mockito.mock(java.security.cert.X509Certificate.class);
    PowerMockito.when(CertificateMgtUtils.convert(x509Certificate)).thenReturn(Optional.of(x509CertificateJava));
    X509Certificate[] sslCertObject = new X509Certificate[] { x509Certificate };
    Mockito.when(axis2MsgCntxt.getProperty(NhttpConstants.SSL_CLIENT_AUTH_CERT_X509)).thenReturn(sslCertObject);
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    X509Certificate x509CertificateUnMatched = Mockito.mock(X509Certificate.class);
    java.security.cert.X509Certificate x509CertificateUnMatchedJava = Mockito.mock(java.security.cert.X509Certificate.class);
    PowerMockito.when(CertificateMgtUtils.convert(x509CertificateUnMatched)).thenReturn(Optional.of(x509CertificateUnMatchedJava));
    PowerMockito.when(X509CertUtils.computeSHA256Thumbprint(x509CertificateJava)).thenReturn(new Base64URL(CERT_HASH));
    PowerMockito.when(X509CertUtils.computeSHA256Thumbprint(x509CertificateUnMatchedJava)).thenReturn(new Base64URL(encodedCertificateUnmatched.toString()));
    signedJWTInfo.setX509ClientCertificate(x509CertificateUnMatched);
    // Mock the properties read from the deployment.toml
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_CERTIFICATE_BOUND_ACCESS_TOKEN)).thenReturn("true");
    try {
        JWTValidationInfo validatedInfo = jwtValidator.validateToken(signedJWTInfo);
        assertFalse(validatedInfo.isValid(), "JWT certificate bound access token validation successful even if the certificate thumbprint" + " is incorrect.");
    } catch (APIManagementException e) {
        Assert.fail();
    }
    // validate with correct certificate thumbprint
    signedJWTInfo.setX509ClientCertificate(x509Certificate);
    try {
        JWTValidationInfo validatedInfo = jwtValidator.validateToken(signedJWTInfo);
        assertTrue(validatedInfo.isValid(), "JWT certificate bound access token validation failed with the correct certificate thumbprint.");
    } catch (APIManagementException e) {
        Assert.fail();
    }
    // Test when certificate bound access token validation is enabled and cnf thumbprint validation is successful
    // when client certificate is added in the trust store
    signedJWTInfo.setX509ClientCertificate(null);
    headers.put(BASE64_ENCODED_CLIENT_CERTIFICATE_HEADER, BASE64_ENCODED_CERT);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) JWKSConfigurationDTO(org.wso2.carbon.apimgt.common.gateway.dto.JWKSConfigurationDTO) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) HashMap(java.util.HashMap) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) TokenIssuerDto(org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto) X509Certificate(javax.security.cert.X509Certificate) Base64URL(com.nimbusds.jose.util.Base64URL) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) CertificateManagerImplTest(org.wso2.carbon.apimgt.impl.certificatemgt.CertificateManagerImplTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 7 with Base64URL

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

the class NimbusJwtEncoderTests method encodeWhenSuccessThenDecodes.

@Test
public void encodeWhenSuccessThenDecodes() throws Exception {
    // @formatter:off
    RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY).keyID("rsa-jwk-1").x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-1")).build();
    this.jwkList.add(rsaJwk);
    // @formatter:on
    JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
    JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
    Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(jwsHeader.getAlgorithm());
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256)).isEqualTo(rsaJwk.getX509CertSHA256Thumbprint().toString());
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CTY)).isNull();
    assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull();
    assertThat(encodedJws.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer());
    assertThat(encodedJws.getSubject()).isEqualTo(jwtClaimsSet.getSubject());
    assertThat(encodedJws.getAudience()).isEqualTo(jwtClaimsSet.getAudience());
    assertThat(encodedJws.getExpiresAt()).isEqualTo(jwtClaimsSet.getExpiresAt());
    assertThat(encodedJws.getNotBefore()).isEqualTo(jwtClaimsSet.getNotBefore());
    assertThat(encodedJws.getIssuedAt()).isEqualTo(jwtClaimsSet.getIssuedAt());
    assertThat(encodedJws.getId()).isEqualTo(jwtClaimsSet.getId());
    assertThat(encodedJws.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws.getTokenValue());
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) Base64URL(com.nimbusds.jose.util.Base64URL) Test(org.junit.jupiter.api.Test)

Example 8 with Base64URL

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

the class JwtDecoderProviderConfigurationUtilsTests method getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses.

@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses() throws Exception {
    JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
    // Test parameters are from Anders Rundgren, public only
    ECKey ecKey = new ECKey.Builder(Curve.P_256, new Base64URL("3l2Da_flYc-AuUTm2QzxgyvJxYM_2TeB9DMlwz7j1PE"), new Base64URL("-kjT7Wrfhwsi9SG6H4UXiyUiVE9GHCLauslksZ3-_t0")).keyUse(KeyUse.SIGNATURE).build();
    RSAKey rsaKey = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.ENCRYPTION).build();
    given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Arrays.asList(ecKey, rsaKey));
    Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
    assertThat(algorithms).contains(SignatureAlgorithm.ES256, SignatureAlgorithm.ES384, SignatureAlgorithm.ES512);
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) RSAKey(com.nimbusds.jose.jwk.RSAKey) SecurityContext(com.nimbusds.jose.proc.SecurityContext) ECKey(com.nimbusds.jose.jwk.ECKey) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) Base64URL(com.nimbusds.jose.util.Base64URL) Test(org.junit.jupiter.api.Test)

Aggregations

Base64URL (com.nimbusds.jose.util.Base64URL)8 Test (org.junit.jupiter.api.Test)4 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 JOSEException (com.nimbusds.jose.JOSEException)2 JWSHeader (com.nimbusds.jose.JWSHeader)2 HashMap (java.util.HashMap)2 Algorithm (com.nimbusds.jose.Algorithm)1 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)1 ECKey (com.nimbusds.jose.jwk.ECKey)1 JWKSelector (com.nimbusds.jose.jwk.JWKSelector)1 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)1 RemoteJWKSet (com.nimbusds.jose.jwk.source.RemoteJWKSet)1 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)1 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)1 SecurityContext (com.nimbusds.jose.proc.SecurityContext)1 Base64 (com.nimbusds.jose.util.Base64)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ConfigurableJWTProcessor (com.nimbusds.jwt.proc.ConfigurableJWTProcessor)1