Search in sources :

Example 11 with Claim

use of org.wso2.carbon.user.api.Claim in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImpl method getOrganizationClaim.

/**
 * Get the organization claim from authenticators configuration
 *
 * @return OrganizationClaimAttribute value configured in authenticators.xml
 */
private String getOrganizationClaim() {
    AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
    AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME);
    if (authenticatorConfig != null) {
        Map<String, String> configParameters = authenticatorConfig.getParameters();
        if (configParameters.containsKey(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE)) {
            return configParameters.get(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE);
        }
    }
    return APIConstants.DEFAULT_ORGANIZATION_CLAIM_NAME;
}
Also used : AuthenticatorsConfiguration(org.wso2.carbon.core.security.AuthenticatorsConfiguration) XSString(org.opensaml.core.xml.schema.XSString)

Example 12 with Claim

use of org.wso2.carbon.user.api.Claim in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImpl method getGroupingIdentifierList.

@Override
public String[] getGroupingIdentifierList(String loginResponse) {
    if (log.isDebugEnabled()) {
        log.debug("Login response " + loginResponse);
    }
    ByteArrayInputStream samlResponseStream = null;
    DocumentBuilder docBuilder;
    String username = "";
    String organization = "";
    String[] groupIdArray = null;
    try {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI);
        if (StringUtils.isBlank(claim)) {
            claim = "http://wso2.org/claims/organization";
        }
        samlResponseStream = getByteArrayInputStream(loginResponse);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        builderFactory.setNamespaceAware(true);
        docBuilder = builderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(samlResponseStream);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        Response response = (Response) unmarshaller.unmarshall(element);
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
        String isSAML2Enabled = System.getProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION);
        if (!StringUtils.isEmpty(isSAML2Enabled) && Boolean.parseBoolean(isSAML2Enabled)) {
            organization = getOrganizationFromSamlAssertion(assertions);
        } else {
            RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
            String tenantDomain = MultitenantUtils.getTenantDomain(username);
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
            UserStoreManager manager = realm.getUserStoreManager();
            organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
        }
        if (log.isDebugEnabled()) {
            log.debug("User organization " + organization);
        }
        if (organization != null) {
            if (organization.contains(",")) {
                groupIdArray = organization.split(",");
                for (int i = 0; i < groupIdArray.length; i++) {
                    groupIdArray[i] = groupIdArray[i].toString().trim();
                }
            } else {
                organization = organization.trim();
                groupIdArray = new String[] { organization };
            }
        } else {
            // If claim is null then returning a empty string
            groupIdArray = new String[] {};
        }
    } catch (ParserConfigurationException e) {
        String msg = "Error while parsing SAML Assertion";
        log.error(msg, e);
    } catch (UnmarshallingException e) {
        String msg = "Error while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (SAXException e) {
        String msg = "Parsing exception  occur while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (IOException e) {
        String msg = "IO exception happen while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (UserStoreException e) {
        log.error("User store exception occurred for user" + username, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while checking user existence for " + username, e);
    } finally {
        if (samlResponseStream != null) {
            try {
                samlResponseStream.close();
            } catch (IOException e) {
                // Ignore
                log.error("ERROR_CLOSING_STREAM");
            }
        }
    }
    return groupIdArray;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) XSString(org.opensaml.core.xml.schema.XSString) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) Assertion(org.opensaml.saml.saml2.core.Assertion) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) IOException(java.io.IOException) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 13 with Claim

use of org.wso2.carbon.user.api.Claim in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImpl method getGroupingIdentifiers.

public String getGroupingIdentifiers(String loginResponse) {
    if (log.isDebugEnabled()) {
        log.debug("Login response " + loginResponse);
    }
    ByteArrayInputStream samlResponseStream = null;
    DocumentBuilder docBuilder;
    String username = "";
    String organization = "";
    try {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI);
        if (StringUtils.isBlank(claim)) {
            claim = "http://wso2.org/claims/organization";
        }
        samlResponseStream = getByteArrayInputStream(loginResponse);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        builderFactory.setNamespaceAware(true);
        docBuilder = builderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(samlResponseStream);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        Response response = (Response) unmarshaller.unmarshall(element);
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
        UserStoreManager manager = realm.getUserStoreManager();
        organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
        if (log.isDebugEnabled()) {
            log.debug("User organization " + organization);
        }
        if (organization != null) {
            organization = tenantDomain + "/" + organization.trim();
        }
    } catch (ParserConfigurationException e) {
        String msg = "Error while parsing SAML Assertion";
        log.error(msg, e);
    } catch (UnmarshallingException e) {
        String msg = "Error while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (SAXException e) {
        String msg = "Parsing exception  occur while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (IOException e) {
        String msg = "IO exception happen while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (UserStoreException e) {
        log.error("User store exception occurred for user" + username, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while checking user existence for " + username, e);
    } finally {
        if (samlResponseStream != null) {
            try {
                samlResponseStream.close();
            } catch (IOException e) {
                // Ignore
                log.error("ERROR_CLOSING_STREAM");
            }
        }
    }
    return organization;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) XSString(org.opensaml.core.xml.schema.XSString) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) Assertion(org.opensaml.saml.saml2.core.Assertion) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) IOException(java.io.IOException) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 14 with Claim

use of org.wso2.carbon.user.api.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 15 with Claim

use of org.wso2.carbon.user.api.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)

Aggregations

UserRealm (org.wso2.carbon.user.core.UserRealm)5 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)5 ArrayList (java.util.ArrayList)4 XSString (org.opensaml.core.xml.schema.XSString)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Assertion (org.opensaml.saml.saml2.core.Assertion)3 Response (org.opensaml.saml.saml2.core.Response)3 Subject (org.opensaml.saml.saml2.core.Subject)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 AuthenticatorsConfiguration (org.wso2.carbon.core.security.AuthenticatorsConfiguration)3 UserStoreException (org.wso2.carbon.user.api.UserStoreException)3 UserStoreException (org.wso2.carbon.user.core.UserStoreException)3 Claim (org.wso2.carbon.user.core.claim.Claim)3 RemoteException (java.rmi.RemoteException)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2