Search in sources :

Example 6 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImplTest method getGroupingIdentifierListTestCase.

@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException, UnmarshallingException, UserStoreException {
    String claim = "http://wso2.org/claims/organization";
    String organizationValue = "organization";
    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");
    System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).thenReturn("http://wso2.org/claims/organization");
    System.setProperty("carbon.home", "");
    PrivilegedCarbonContext carbonContext;
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
    PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);
    AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
    List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
    PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);
    Attribute mockAttribute = PowerMockito.mock(Attribute.class);
    List<Attribute> attributesList = Collections.singletonList(mockAttribute);
    PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);
    XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
    PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
    List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
    AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName", "namespacePrefix");
    String sampleAttrValue = "MockedAuthParamSampleAttribute";
    mockedAttributedStringImpl.setValue(sampleAttrValue);
    List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
    XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
    PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
    List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
    List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
    AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito.mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
    PowerMockito.when(mockAttribute.getAttributeValues()).thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues, mockedXSAnyImplAttributeValues);
    PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
    AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito.mock(AuthenticatorsConfiguration.class);
    PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
    Map<String, String> mockedConfigParameters = new HashMap<String, String>();
    mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
    PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
    PowerMockito.when(mockedAuthenticatorsConfiguration.getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME)).thenReturn(mockedAuthenticatorConfig);
    PowerMockito.when(mockAttribute.getName()).thenReturn(claim);
    String[] organizations = samlGroupIDExtractor.getGroupingIdentifierList("test");
    Assert.assertEquals(organizationValue, organizations[0]);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Attribute(org.opensaml.saml.saml2.core.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) XSAnyImpl(org.opensaml.core.xml.schema.impl.XSAnyImpl) AttributedStringImpl(org.opensaml.soap.wssecurity.impl.AttributedStringImpl) NameID(org.opensaml.saml.saml2.core.NameID) AuthenticatorsConfiguration(org.wso2.carbon.core.security.AuthenticatorsConfiguration) Assertion(org.opensaml.saml.saml2.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 7 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim 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 8 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-apimgt by wso2.

the class JWTGenerator method convertClaimMap.

protected Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) throws APIManagementException {
    Map<String, String> userClaims = new HashMap<>();
    Map<String, String> userClaimsCopy = new HashMap<>();
    for (Map.Entry<ClaimMapping, String> entry : userAttributes.entrySet()) {
        Claim claimObject = entry.getKey().getLocalClaim();
        if (claimObject == null) {
            claimObject = entry.getKey().getRemoteClaim();
        }
        userClaims.put(claimObject.getClaimUri(), entry.getValue());
        userClaimsCopy.put(claimObject.getClaimUri(), entry.getValue());
    }
    String convertClaimsFromOIDCtoConsumerDialect = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getFirstProperty(APIConstants.CONVERT_CLAIMS_TO_CONSUMER_DIALECT);
    if (convertClaimsFromOIDCtoConsumerDialect != null && !Boolean.parseBoolean(convertClaimsFromOIDCtoConsumerDialect)) {
        return userClaims;
    }
    int tenantId = APIUtil.getTenantId(username);
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    String dialect;
    ClaimsRetriever claimsRetriever = getClaimsRetriever();
    if (claimsRetriever != null) {
        dialect = claimsRetriever.getDialectURI(username);
    } else {
        dialect = getDialectURI();
    }
    // (key) configuredDialectClaimURI -> (value)
    Map<String, String> configuredDialectToCarbonClaimMapping = null;
    // carbonClaimURI
    // (key) carbonClaimURI ->  value (oidcClaimURI)
    Map<String, String> carbonToOIDCclaimMapping = null;
    Set<String> claimUris = new HashSet<String>(userClaims.keySet());
    try {
        carbonToOIDCclaimMapping = new ClaimMetadataHandler().getMappingsMapFromOtherDialectToCarbon(OIDC_DIALECT_URI, claimUris, tenantDomain, true);
        configuredDialectToCarbonClaimMapping = ClaimManagerHandler.getInstance().getMappingsMapFromCarbonDialectToOther(dialect, carbonToOIDCclaimMapping.keySet(), tenantDomain);
    } catch (ClaimMetadataException e) {
        String error = "Error while mapping claims from Carbon dialect to " + OIDC_DIALECT_URI + " dialect";
        throw new APIManagementException(error, e);
    } catch (ClaimManagementException e) {
        String error = "Error while mapping claims from configured dialect to Carbon dialect";
        throw new APIManagementException(error, e);
    }
    for (Map.Entry<String, String> oidcClaimValEntry : userClaims.entrySet()) {
        for (Map.Entry<String, String> carbonToOIDCEntry : carbonToOIDCclaimMapping.entrySet()) {
            if (oidcClaimValEntry.getKey().equals(carbonToOIDCEntry.getValue())) {
                for (Map.Entry<String, String> configuredToCarbonEntry : configuredDialectToCarbonClaimMapping.entrySet()) {
                    if (configuredToCarbonEntry.getValue().equals(carbonToOIDCEntry.getKey())) {
                        userClaimsCopy.remove(oidcClaimValEntry.getKey());
                        userClaimsCopy.put(configuredToCarbonEntry.getKey(), oidcClaimValEntry.getValue());
                    }
                }
            }
        }
    }
    return userClaimsCopy;
}
Also used : ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ClaimMetadataHandler(org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataHandler) ClaimsRetriever(org.wso2.carbon.apimgt.impl.token.ClaimsRetriever) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClaimManagementException(org.wso2.carbon.claim.mgt.ClaimManagementException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Claim(org.wso2.carbon.identity.application.common.model.Claim) HashSet(java.util.HashSet)

Example 9 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-apimgt by wso2.

the class APIUtil method getDefaultClaimMappings.

public static List<ClaimMappingDto> getDefaultClaimMappings() {
    List<ClaimMappingDto> claimMappingDtoList = new ArrayList<>();
    try (InputStream resourceAsStream = APIUtil.class.getClassLoader().getResourceAsStream("claimMappings/default-claim-mapping.json")) {
        String content = IOUtils.toString(resourceAsStream);
        Map<String, String> claimMapping = new Gson().fromJson(content, Map.class);
        claimMapping.forEach((remoteClaim, localClaim) -> {
            claimMappingDtoList.add(new ClaimMappingDto(remoteClaim, localClaim));
        });
    } catch (IOException e) {
        log.error("Error while reading default-claim-mapping.json", e);
    }
    return claimMappingDtoList;
}
Also used : ClaimMappingDto(org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 10 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-apimgt by wso2.

the class DefaultClaimsRetrieverTestCase method testGetClaimsWhenCacheEmpty.

@Test
public void testGetClaimsWhenCacheEmpty() throws Exception {
    DefaultClaimsRetriever defaultClaimsRetriever = new DefaultClaimsRetriever();
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_CLAIM_CACHE_EXPIRY)).thenReturn(null);
    Cache cache = Mockito.mock(Cache.class);
    Mockito.when(cacheManager.getCache(APIConstants.CLAIMS_APIM_CACHE)).thenReturn(cache);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTenantId(USER_NAME)).thenReturn(TENANT_ID);
    Claim claim1 = new Claim();
    claim1.setClaimUri("http://wso2.org/claim1");
    Claim claim2 = new Claim();
    claim2.setClaimUri("http://wso2.com/claim2");
    SortedMap<String, String> claimValues = new TreeMap<String, String>();
    claimValues.put("claim1", "http://wso2.org/claim1");
    claimValues.put("claim2", "http://wso2.org/claim2");
    PowerMockito.when(APIUtil.getClaims(USER_NAME, TENANT_ID, DEFAULT_DIALECT_URI)).thenReturn(claimValues);
    SortedMap<String, String> claims = defaultClaimsRetriever.getClaims(USER_NAME);
    Assert.assertNotNull(claims);
    Assert.assertEquals(claimValues, claims);
}
Also used : TreeMap(java.util.TreeMap) Claim(org.wso2.carbon.user.api.Claim) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

HashMap (java.util.HashMap)112 ArrayList (java.util.ArrayList)89 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)66 UserStoreException (org.wso2.carbon.user.api.UserStoreException)65 Test (org.testng.annotations.Test)63 ClaimMetadataException (org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException)55 Map (java.util.Map)49 PreparedStatement (java.sql.PreparedStatement)48 SQLException (java.sql.SQLException)43 LocalClaim (org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim)34 RealmService (org.wso2.carbon.user.core.service.RealmService)30 UserRealm (org.wso2.carbon.user.core.UserRealm)29 Claim (org.wso2.carbon.user.api.Claim)28 UserStoreException (org.wso2.carbon.user.core.UserStoreException)28 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)28 ResultSet (java.sql.ResultSet)27 Connection (java.sql.Connection)25 ClaimConfig (org.wso2.carbon.identity.application.common.model.ClaimConfig)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)24 Claim (org.wso2.carbon.identity.application.common.model.Claim)24