Showing posts with label LDAP. Show all posts
Showing posts with label LDAP. Show all posts

Sunday, June 1, 2014

Getting User Attributes in SAML2 Bearer Assertion Profile for OAuth 2.0 using JWT Token Generation

We can configure WSO2 API Manager to send user attributes to backend API, if the internal users of API Manager consumes the API using obtained OAuth token. That process is described in https://docs.wso2.org/display/AM170/Passing+Enduser+attributes+to+the+Backend+Using+JWT. JSON Web Token(JWT) tokens are used in this.

But when users get OAuth token using SAML2 Bearer Assertion Profile for OAuth 2.0 how can we do that? What we need to do is share the user store with IS as well as API Manger. That kind of a architecture is given below.


SAML2 Bearer Assertion Profile for OAuth 2.0 with WSO2 Identity Server 5.0.0 and WSO2 API Manger 1.7.0

WSO2 product stack supports SAML2 Bearer Assertion Profile for OAuth 2.0. You can find lot of details about it in https://docs.wso2.org/display/IS460/SAML2+Bearer+Assertion+Profile+for+OAuth+2.0. What happens in here actually is a user can get a SAML token from WSO2 Identity Server by authenticating. After that user can give that SAML token to API Manger to get an OAuth token without going for authentication. To do that WSO2 Identity Server have to be a trusted identity provider for WSO2 API Manager. I will explain how to do it in these products.

You need,
Here a sample web application is using SAML SSO to authenticate it's users using  WSO2 Identity Server  and use SAML2 Bearer Assertion Profile to get OAuth token from WSO2 API Manager. Those tokens are used to query a REST API published in API Manager.

To understand this more I will expalin the flow,
  • When a user access the sample web application using this kind of urls http://example.com/mobile, they will be redirected to WSO2 Identity Server authentication page.
  • When users authenticate them self in the login UI WSO2 Identity Server will redirect the request back to web application with a SAML response like this,
<?xml version="1.0" encoding="UTF-8"?> 
<saml2:Assertion xmlns:saml2="urn:oasis:names: tc:SAML:2.0:assertion" ID="hnpnedgkgdbhinomeabplbjdnhlffjbbckodpkhl" IssueInstant="2014-05-31T15:41:03.665Z" Version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">localhost</saml2:Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
            <ds:Reference URI="#hnpnedgkgdbhinomeabplbjdnhlffjbbckodpkhl">
                <ds:Transforms>
                    <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                        <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="xs"/>
                    </ds:Transform>
                </ds:Transforms>
                <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                <ds:DigestValue>KaUzRnwIJfhVboyWpcgg555ea0Y=</ds:DigestValue>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>
            L3jOrttx7+Vb6iBnDV6hu4GRoGDX6k1U2Z+C7XLh7+jgvq53/N7Ro0rY4d4GiJJb5gOcAg3f8qt+gKQbAvcjvbJCRW1x4GFZ0au4iqZUSbHOPYPiIT4mYzxrmZg+cynVN+mrJCEEFdhFaP/3yPITeeapP9Yqp3QvtnbRC6s8ejk=
        </ds:SignatureValue>
        <ds:KeyInfo>
            <ds:X509Data>
                <ds:X509Certificate>
                    MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBg
                </ds:X509Certificate>
            </ds:X509Data>
        </ds:KeyInfo>
    </ds:Signature>
    <saml2:Subject>
        <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">demo</saml2:NameID>
        <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
            <saml2:SubjectConfirmationData InResponseTo="0" NotOnOrAfter="2014-05-31T15:46:03.664Z" Recipient="http://example.com/mobile/mobile.jsp"/>
        </saml2:SubjectConfirmation>
        <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
            <saml2:SubjectConfirmationData InResponseTo="0" NotOnOrAfter="2014-05-31T15:46:03.664Z" Recipient="https://IP:9448/oauth2/token"/>
        </saml2:SubjectConfirmation>
    </saml2:Subject>
    <saml2:Conditions NotBefore="2014-05-31T15:41:03.665Z" NotOnOrAfter="2014-05-31T15:46:03.664Z"
        <saml2:AudienceRestriction>
            <saml2:Audience>exampleMobile</saml2:Audience>             
	    <saml2:Audience>https://IP:9448/oauth2/token</saml2:Audience>
        </saml2:AudienceRestriction>
    </saml2:Conditions>
    <saml2:AuthnStatement AuthnInstant="2014-05-31T15:41:03.665Z" SessionIndex="57c87332-97f2-4fe1-bb70-326c0e59fd36">
        <saml2:AuthnContext>
            <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef>
        </saml2:AuthnContext>
    </saml2:AuthnStatement>
    <saml2:AttributeStatement>
        <saml2:Attribute Name="http://wso2.org/claims/role"
                         NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
            <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">company_admin,Internal/everyone</saml2:AttributeValue>
        </saml2:Attribute>
        <saml2:Attribute Name="http://wso2.org/claims/organization" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
            <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">5386e408b35805c8649e08b8</saml2:AttributeValue>
        </saml2:Attribute>
    </saml2:AttributeStatement>
</saml2:Assertion> 
  • By giving this to OAuth token endpoint of API Manger we can get a OAuth token like this,
{"token_type":"bearer","expires_in":3600,"refresh_token":"b75d83e892994882abf3c19cea4db4a2","access_token":"51ee8f8f417f944a4d9c787adc6c260"}
To get this done we need to configure like this,

Step 1 - Start the Identity Server and go to Main Tab > Identity > Service Providers >Add

Enter a Service Provider Name and click Register,


Step 2 - In the next UI select Inbound Authentication Configuration > SAML2 Web SSO Configuration >  Configure

Step 3 - Fill the Like below. Assertion consumer url will be the web application url which will IS sends the SAML response. Give the API Manager's OAuth token url as audience restriction as well as recipient restriction. Also check Enable Attribute Profile to get user attributes with SAML response. And click register.


Step 4 - In the next UI select Claim Configuration > Requested Claims > Add Claim URI. Add the user claims which you need to get it with SAML response to the web application.

Step 5 - Click the Update button to save the Service Provider.

Now the SAML SSO configuration from Identity Server side is done. The web application can be configured using the SAML SSO servlet filter given by the Identity Server it self. That will check user's authentication and will redirect to IS and will process responses form IS. You can find more about that by looking at the code given in https://docs.wso2.org/display/IS500/Configuring+SAML2+SSO.

Now we need to configure API Manger side.
 
Step 1 - Start the API Manger and go to Main Tab > Identity > Identity Providers >Add

Give a Identity Provider Name and  You can keep Alias empty. Also you need to upload the public certificate of Identity Server. You can get it by executing following command in WSO2 IS Home/repository/resources/security/. Then public certificate will be saved in wso2pem.pem file.
keytool -export -alias wso2carbon -file wso2pem.pem -keystore wso2carbon.jks
Then click on Federated Authenticators tab.
Step 2 - In that UI click on SAML2 Web SSO Configuration

In that you need to give the Issuer ID of the SAML config in IS side ad Identity Provider Entity Id.

Step 3 - And then click register.

Now you are ready to go. All the configurations which need to do SAML 2 Bearer Assertion Profile is done. You can use these articles to setup a OAuth application in API Manger to consume APIs.
After doing that follow the steps given in Invoking Token API to generate tokens section of this article. https://docs.wso2.org/display/AM170/Token+API#TokenAPI-ExchangingSAML2bearertokenswithOAuth2%28SAMLextensiongranttype%29. By doing that you can get a OAuth token as above.

How to configure LDAP with WSO2 Identity Server with SCIM support - The easy way

If you want to setup your user store in a LDAP and want to integrate it with WSO2 Identity Server which support SCIM operations, you need to do claim mapping as described in this post http://sureshatt.blogspot.com/2013/06/scim-user-provisioning-with-wso2.html. But if you are going to support lot of user attributes in your user store and complex user operations with SCIM, this mapping and configuration will be a headache for you.

Thus I will show you a easy way to setup your own LDAP and WSO2 Identity Server to support all these. I am using the configurations in built in LDAP of WSO2 Identity Server.

What you need,
As  you know the attributes assigned to LDAP users are defined in object classes of LDAP. If you want to add more attributes, You need to add your own object classes. You can find mroe details about those in these articles,

http://hasini-gunasinghe.blogspot.com/2011/02/how-to-introduce-custom-attributes-to.html
http://hasini-gunasinghe.blogspot.com/2011/04/how-to-introduce-custom-object-class-to.html

After adding these classes you need do lot of mapping to integrate LDAP with SCIM and other complex operation support in WSO2 Identity Server. Believe me its hectic. So what we can do? What we can do is setting up our LDAP with the built in LDAP object classes of WSO2 Identity Server. Those classes define the necessary attributes to support complex operation like SCIM etc. You can find these classes here,
You can import to these classes to your ApacheDS LDAP using  Apache Directory Studio. In the 'LDAP Browser' window in Apache Directory Studio, Right click on the 'ou=schema' context entry, select 'Import->LDIF Import' and point to above files and import them.After that your LDAP will support all the user attributes as we see in built in LDAP of WSO2 Identity Server.

After that integrate the LDAP to WSO2 Identity Server by changing user-mgt.xml in WSO2 Identity Server Home/repository/conf. You have to use the read-write ldap mode like this,

        <UserStoreManager class="org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager">
            <Property name="TenantManager">org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager</Property>
            <Property name="ConnectionURL">ldap://IP:10389</Property>
            <Property name="Disabled">false</Property>                       
            <Property name="ConnectionName">uid=admin,ou=system</Property>
            <Property name="ConnectionPassword">your_password</Property>
            <Property name="passwordHashMethod">PLAIN_TEXT</Property>
            <Property name="UserNameListFilter">(objectClass=person)</Property>
            <Property name="UserEntryObjectClass">identityPerson</Property>
            <Property name="UserSearchBase">ou=Users,dc=example,dc=com</Property>
            <Property name="UserNameSearchFilter">(&amp;(objectClass=person)(uid=?))</Property>
            <Property name="UserNameAttribute">uid</Property>
            <Property name="UsernameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
            <Property name="UsernameJavaScriptRegEx">^[\S]{3,30}$</Property>
            <Property name="RolenameJavaScriptRegEx">^[\S]{3,30}$</Property>
            <Property name="RolenameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
            <Property name="PasswordJavaScriptRegEx">^[\S]{5,30}$</Property>
            <Property name="ReadGroups">true</Property>
            <Property name="WriteGroups">true</Property>
            <Property name="EmptyRolesAllowed">false</Property>
            <Property name="GroupSearchBase">ou=Groups,dc=example,dc=com</Property>
            <Property name="GroupNameListFilter">(objectClass=groupOfNames)</Property>
            <Property name="GroupEntryObjectClass">groupOfNames</Property>
            <Property name="GroupNameSearchFilter">(&amp;(objectClass=groupOfNames)(cn=? </Property>
            <Property name="GroupNameAttribute">cn</Property>
            <Property name="SharedGroupNameAttribute">cn</Property>
            <Property name="SharedGroupSearchBase">ou=SharedGroups,dc=example,dc=com</Property>
            <Property name="SharedGroupEntryObjectClass">groupOfNames</Property>
            <Property name="SharedGroupNameListFilter">(objectClass=groupOfNames)</Property>
            <Property name="SharedGroupNameSearchFilter">(&amp;(objectClass=groupOfNames)(cn=?))</Property>
            <Property name="SharedTenantNameListFilter">(objectClass=organizationalUnit)</Property>
            <Property name="SharedTenantNameAttribute">ou</Property>
            <Property name="SharedTenantObjectClass">organizationalUnit</Property>
            <Property name="MembershipAttribute">member</Property>
            <Property name="UserRolesCacheEnabled">true</Property>
            <Property name="ReplaceEscapeCharactersAtUserLogin">true</Property>
            <Property name="MaxRoleNameListLength">100</Property>
            <Property name="MaxUserNameListLength">100</Property>
            <Property name="SCIMEnabled">true</Property>
        </UserStoreManager>



Also you need to create a admin user in your user search base. That is to log in to the management console. To understand more about the internal LDAP of WSO2 Identity Server you can connect to it via Apache Directory Studio. You can refer,

http://stackoverflow.com/questions/22494921/wso2-identity-server-ldap-browsing
http://stackoverflow.com/questions/11841761/browsing-internal-ldap-of-wso2-identity-server

Hope this helps you to setup your user store easily.