Search in sources :

Example 1 with TokenIssuerDto

use of org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setJWTTokenIssuers.

private void setJWTTokenIssuers(OMElement omElement) {
    Iterator tokenIssuersElement = omElement.getChildrenWithLocalName(APIConstants.TokenIssuer.TOKEN_ISSUER);
    while (tokenIssuersElement.hasNext()) {
        OMElement issuerElement = (OMElement) tokenIssuersElement.next();
        String issuer = issuerElement.getAttributeValue(new QName("issuer"));
        OMElement consumerKeyClaimElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.CONSUMER_KEY_CLAIM));
        OMElement scopesElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.SCOPES_CLAIM));
        TokenIssuerDto tokenIssuerDto = new TokenIssuerDto(issuer);
        if (consumerKeyClaimElement != null) {
            tokenIssuerDto.setConsumerKeyClaim(consumerKeyClaimElement.getText());
        }
        if (scopesElement != null) {
            tokenIssuerDto.setScopesClaim(scopesElement.getText());
        }
        OMElement jwksConfiguration = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.JWKS_CONFIGURATION));
        if (jwksConfiguration != null) {
            JWKSConfigurationDTO jwksConfigurationDTO = tokenIssuerDto.getJwksConfigurationDTO();
            jwksConfigurationDTO.setEnabled(true);
            jwksConfigurationDTO.setUrl(jwksConfiguration.getFirstChildWithName(new QName(APIConstants.TokenIssuer.JWKSConfiguration.URL)).getText());
        }
        OMElement claimMappingsElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.CLAIM_MAPPINGS));
        if (claimMappingsElement != null) {
            OMAttribute disableDefaultClaimMappingAttribute = claimMappingsElement.getAttribute(new QName("disable-default-claim-mapping"));
            if (disableDefaultClaimMappingAttribute != null) {
                String disableDefaultClaimMapping = disableDefaultClaimMappingAttribute.getAttributeValue();
                tokenIssuerDto.setDisableDefaultClaimMapping(Boolean.parseBoolean(disableDefaultClaimMapping));
            }
            Iterator claimMapping = claimMappingsElement.getChildrenWithName(new QName(APIConstants.TokenIssuer.CLAIM_MAPPING));
            while (claimMapping.hasNext()) {
                OMElement claim = (OMElement) claimMapping.next();
                OMElement remoteClaimElement = claim.getFirstChildWithName(new QName(APIConstants.TokenIssuer.ClaimMapping.REMOTE_CLAIM));
                OMElement localClaimElement = claim.getFirstChildWithName(new QName(APIConstants.TokenIssuer.ClaimMapping.LOCAL_CLAIM));
                if (remoteClaimElement != null && localClaimElement != null) {
                    String remoteClaim = remoteClaimElement.getText();
                    String localClaim = localClaimElement.getText();
                    if (StringUtils.isNotEmpty(remoteClaim) && StringUtils.isNotEmpty(localClaim)) {
                        tokenIssuerDto.getClaimConfigurations().put(remoteClaim, new ClaimMappingDto(remoteClaim, localClaim));
                    }
                }
            }
        }
        jwtConfigurationDto.getTokenIssuerDtoMap().put(tokenIssuerDto.getIssuer(), tokenIssuerDto);
    }
}
Also used : ClaimMappingDto(org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto) JWKSConfigurationDTO(org.wso2.carbon.apimgt.common.gateway.dto.JWKSConfigurationDTO) QName(javax.xml.namespace.QName) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) TokenIssuerDto(org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 2 with TokenIssuerDto

use of org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto in project carbon-apimgt by wso2.

the class ServerStartupListener method completedServerStartup.

@Override
public void completedServerStartup() {
    copyToExtensions();
    APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        String enableKeyManagerRetrieval = apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_KEY_MANAGER_RETRIVAL);
        if (JavaUtils.isTrueExplicitly(enableKeyManagerRetrieval)) {
            startConfigureKeyManagerConfigurations();
        }
        Map<String, TokenIssuerDto> tokenIssuerDtoMap = apiManagerConfiguration.getJwtConfigurationDto().getTokenIssuerDtoMap();
        tokenIssuerDtoMap.forEach((issuer, tokenIssuer) -> KeyManagerHolder.addGlobalJWTValidators(tokenIssuer));
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) TokenIssuerDto(org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto)

Example 3 with TokenIssuerDto

use of org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto in project carbon-apimgt by wso2.

the class APIMRestAPICommonComponent method activate.

@Activate
protected void activate(ComponentContext context) {
    Map<String, JWTValidator> jwtValidatorMap = new HashMap<>();
    Map<String, TokenIssuerDto> tokenIssuerMap = APIMConfigUtil.getTokenIssuerMap();
    tokenIssuerMap.forEach((issuer, tokenIssuer) -> {
        JWTValidator jwtValidator = new JWTValidatorImpl();
        jwtValidator.loadTokenIssuerConfiguration(tokenIssuer);
        jwtValidatorMap.put(issuer, jwtValidator);
    });
    ServiceReferenceHolder.getInstance().setJwtValidatorMap(jwtValidatorMap);
}
Also used : HashMap(java.util.HashMap) JWTValidatorImpl(org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl) JWTValidator(org.wso2.carbon.apimgt.impl.jwt.JWTValidator) TokenIssuerDto(org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto)

Example 4 with TokenIssuerDto

use of org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto in project carbon-apimgt by wso2.

the class JWTValidatorImpl method loadTokenIssuerConfiguration.

@Override
public void loadTokenIssuerConfiguration(TokenIssuerDto tokenIssuerConfigurations) {
    this.tokenIssuer = tokenIssuerConfigurations;
    JWTTransformer jwtTransformer = ServiceReferenceHolder.getInstance().getJWTTransformer(tokenIssuer.getIssuer());
    if (jwtTransformer != null) {
        this.jwtTransformer = jwtTransformer;
    } else {
        this.jwtTransformer = new DefaultJWTTransformer();
    }
    this.jwtTransformer.loadConfiguration(tokenIssuer);
}
Also used : DefaultJWTTransformer(org.wso2.carbon.apimgt.common.gateway.jwttransformer.DefaultJWTTransformer) JWTTransformer(org.wso2.carbon.apimgt.common.gateway.jwttransformer.JWTTransformer) DefaultJWTTransformer(org.wso2.carbon.apimgt.common.gateway.jwttransformer.DefaultJWTTransformer)

Example 5 with TokenIssuerDto

use of org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto 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)

Aggregations

TokenIssuerDto (org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto)5 JWKSConfigurationDTO (org.wso2.carbon.apimgt.common.gateway.dto.JWKSConfigurationDTO)3 JWTValidator (org.wso2.carbon.apimgt.impl.jwt.JWTValidator)3 JWTValidatorImpl (org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl)3 HashMap (java.util.HashMap)2 X509Certificate (javax.security.cert.X509Certificate)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 ClaimMappingDto (org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto)2 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)2 Gson (com.google.gson.Gson)1 JsonElement (com.google.gson.JsonElement)1 Base64URL (com.nimbusds.jose.util.Base64URL)1 Iterator (java.util.Iterator)1 List (java.util.List)1 QName (javax.xml.namespace.QName)1 OMAttribute (org.apache.axiom.om.OMAttribute)1 OMElement (org.apache.axiom.om.OMElement)1 MessageContext (org.apache.synapse.MessageContext)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 Test (org.junit.Test)1