Pages

Sunday, May 12, 2013

shibboleth peoplesoft integration

I have integrated shibboleth with people soft tools 8.5.3. I have followed the step by step approach to integrate shibboleth with people soft. They are

1. Service Provider Installation
2. Registering Service Provider with Identity Provider
3. Verifying Service Provider Configuration
4. Installing and Configuring the Apache Web Logic Plugin
5. Verifying Installation and Configuration Apache Web Logic Plugin
6. Protecting the People Soft Application in Service Provider.
7. Developed the Sign-On People Code Functional Libraries
8. Configuring the WWW_AUTHENTICATION in people tools UI
9. Creating the People Soft User without roles and permission
10. Modifying the People Soft Web Profile.
11. Testing the People soft integration with shibboleth. 



Installation and Configuration Details

Please follow my earlier blog post from step 1 to step 3 to install, configuration, and verifying service provider and lyncs are provided below.

1. Service Provider Installation and Configuration


1.1 Service Provider Installation
1.2 Registering Service Provider with Identity Provider 

Identity Provider Configuration

The following files needs to be configured to enable the external authentication for People Soft. They are

relying-party.xml

Download the service provider meta-data xml file and  add the service provider metadata xml location info to the relying-party.xml under the section <metadata:MetadataProvider. The Sample Configuration of the service provider meta-data file path is given below.
 
<metadata:MetadataProvider id="pspt.liyaqat.com" xsi:type="metadata:FilesystemMetadataProvider"
                          metadataFile="/opt/shibboleth-idp/metadata/pspt.liyaqat.com.xml"/>


In the above example pspt.liyaqat.com is service provider meta data id and this id must be unique for each service provider and specify the service provider meta-data location in the metadataFile attribute and the sample value is /opt/shibboleth-idp/metadata/pspt.liyaqat.com.xml.

attribute-resolver.xml

Define the Identity provider (people soft) releasing attributes to service provider definition in the attribute-resolver.xml. By default attribute definitions info is commented in the xml file. Uncomment the attribute definition which is requested by the service provider and this info is configured in the attribute-filter.xml file.. In my example, the service provider pspt.liyaqat.com going to requuest uid, givenname ,and sn after authentication successful.  I have uncommented the uid, givenname,and sn attributes. The sample configuration is given below

  <resolver:AttributeDefinition xsi:type="ad:Scoped" id="eduPersonPrincipalName" scope="liyaqat.com" sourceAttributeID="uid">
        <resolver:Dependency ref="myLDAP" />
        <resolver:AttributeEncoder xsi:type="enc:SAML1ScopedString" name="urn:mace:dir:attribute-def:eduPersonPrincipalName" />
        <resolver:AttributeEncoder xsi:type="enc:SAML2ScopedString" name="urn:oid:1.3.6.1.4.1.5923.1.1.1.6" friendlyName="eduPersonPrincipalName" />
    </resolver:AttributeDefinition>



 <resolver:AttributeDefinition xsi:type="ad:Simple" id="surname" sourceAttributeID="sn">
        <resolver:Dependency ref="myLDAP" />
        <resolver:AttributeEncoder xsi:type="enc:SAML1String" name="urn:mace:dir:attribute-def:sn" />
        <resolver:AttributeEncoder xsi:type="enc:SAML2String" name="urn:oid:2.5.4.4" friendlyName="sn" />
    </resolver:AttributeDefinition>

 

  <resolver:AttributeDefinition xsi:type="ad:Simple" id="givenName" sourceAttributeID="givenName">
        <resolver:Dependency ref="myLDAP" />
        <resolver:AttributeEncoder xsi:type="enc:SAML1String" name="urn:mace:dir:attribute-def:givenName" />
        <resolver:AttributeEncoder xsi:type="enc:SAML2String" name="urn:oid:2.5.4.42" friendlyName="givenName" />
    </resolver:AttributeDefinition>



Define the LDAP Connector Info


In the above example, dependency reference is myLdap. Please define the Ldap Connector and sample configuration is given below.




<resolver:DataConnector id="myLDAP" xsi:type="dc:LDAPDirectory"
        ldapURL="ldap://idp.liyaqat.com"
        baseDN="ou=people,dc=liyaqat,dc=com"
        principal="cn=Manager,dc=liyaqat,dc=com"
        principalCredential="<Password>">
        <dc:FilterTemplate>
            <![CDATA[
                (uid=$requestContext.principalName)
            ]]>
        </dc:FilterTemplate>
    </resolver:DataConnector>



attribute-filter.xml


Defining the service provider requested attributes in the identity Provider attribute-filter.xml file.The policy configuration is given below. 


<afp:AttributeFilterPolicy>
        <afp:PolicyRequirementRule xsi:type="basic:AttributeRequesterString" value="https://pspt.liyaqat.com/shibboleth" />

        <afp:AttributeRule attributeID="givenName">
            <afp:PermitValueRule xsi:type="basic:ANY" />
        </afp:AttributeRule>
        <afp:AttributeRule attributeID="uid">
            <afp:PermitValueRule xsi:type="basic:ANY"/>
        </afp:AttributeRule>
        <afp:AttributeRule attributeID="surname">
            <afp:PermitValueRule xsi:type="basic:ANY"/>
        </afp:AttributeRule>
   </afp:AttributeFilterPolicy>



In the https://pspt.liyaqat.com/shibboleth is my service provider entity.

handler.xml

Defining the Authentication scheme or Login Handler for the protected resources. The sample configuration is given below.
 
 <ph:LoginHandler xsi:type="ph:UsernamePassword"
                  jaasConfigurationLocation="file:///opt/shibboleth-idp/conf/login.config">
        <ph:AuthenticationMethod>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</ph:AuthenticationMethod>
    </ph:LoginHandler>

 


login.config


Defining the JAAS authentication module for the identity provider. The sample configuration is given blow


ShibUserPassAuth {
      edu.vt.middleware.ldap.jaas.LdapLoginModule required
      ldapUrl="ldap://idp.liyaqat.com"
      baseDn="ou=people,dc=liyaqat,dc=com"
      serviceUser="CN=Manager,dc=liyaqat,dc=com"
      serviceCredential="Passw0rd"
      ssl="false"
      tls="false"
      subtreeSearch="true"
      userFilter="uid={0}";
};



Service Provider Configuration

The following files needs to be configured to enable the external authentication for People Soft. They are

attribute-map.xml

Defining the service provider requested attribute definition in the attribute-map.xml. In my example service provider going to request the three attributes are uid,givenname and sn.


        <Attribute name="urn:oid:0.9.2342.19200300.100.1.1" id="uid"/>
        <Attribute name="urn:oid:2.5.4.4" id="sn"/>
        <Attribute name="urn:oid:2.5.4.42" id="givenName"/>



shibboleth2.xml


Define the application default entity id and remote user for the service provider. The sample configuration is given below.

<ApplicationDefaults entityID="https://pspt.liyaqat.com/shibboleth"
                         REMOTE_USER="uid">


In the above example uid is requesting from the idp server and this uid passed to the people soft sign-on code to enable external shibboleth authentication.

Configuring SSO

configure the SSO idp entity id and discovery idp server url. The sample configuration is given below.

<SSO entityID="https://idp.liyaqat.com/idp/shibboleth"
                 discoveryProtocol="SAMLDS" discoveryURL="https://idp.liyaqat.com/DS/WAYF">
              SAML2 SAML1
            </SSO>


Configure the IDP Metada

Download the IDP metadata file and configure the metadata backing file path, The sample data is given below. 

<MetadataProvider type="XML" uri="https://idp.liyaqat.com/idp/profile/Metadata/SAML"
              backingFilePath="idp-metadata.xml" reloadInterval="7200">
        </MetadataProvider>
  

In the above configuration, https://idp.liyaqat.com/idp/profile/Metadata/SAML is the idp metata url.


Configuring the Certificate

Configuring the Service Provider Certificate key and certificate for the metadata to to encrypt and decrypt the SAML request and response. The Sample configuration is given below.
 
<CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>



The detailed configuration available in the above lync. this is only for reference for people soft external authentication.


1.3 Verifying Service Provider Configuration

2. Apache Web Logic Plugin Configuration

Follow my previous blog to install and configure weblogic apache plugin from step 04 to 05 and lync is given bellow.

Apache Web Server Weblogic Plugin

3. Apache Shibboleth Configuration

Go to the /etc/httpd/conf.d directory and edit the shib.conf file and perform the following task to protect the resource and also enable the canonical names.


3.1 Turn on the Canonical Name and Canonical Port

UseCanonicalName On
UseCanonicalPhysicalPort On 

3.2 Server Name

ServerName <Server Name>

In my example server name is pspt.liyaqat.com

3.3 Protecting a People Soft Resource

Add the following content in the shib.conf file to protect the people soft resource.

<Location /psp/>
  AuthType shibboleth
  ShibRequestSetting requireSession 1
  require shibboleth
  ShibUseHeaders On
</Location>

4. Develop the People Soft Sign On Code

4.1 Clone the FUNLIB_LDAP to FUNCLIB_SHIB

Open the Application Designer and Open the Record Definition FUNCLIB_LDAP. Clone the FUNCLIB_LDAP record definition to FUNCLIB_SHIB. After Cloning the Record definition look like this



4.2 Click the FieldDefault Event and Modify the following functions to enable the External Authentication. In our example is shibboleth.

getWWWAuthConfig() 

Function getWWWAuthConfig()
   &defaultUserId = "PUBUSER";
End-Function;

In the above functions, &defaultUserId is hard coded and the sample user PUBUSER and this user contains no roles and no permissions. Using PUBUSER to establish the connection from web profile to people soft. I am going to create the PUBUSER later. 

 /**
 * To enable the external Authentication SSO in people soft. I am getting the user name that is uid from the request header variable and I am invoking the SetAuthenticationResult( True, Upper(&user), "", False) function to enable the SSO
**/
WWW_AUTHENTICATION()


Function WWW_AUTHENTICATION()
   Local string &user;  
  
   If %PSAuthResult = True And
         &authMethod <> "LDAP" And
         &authMethod <> "SSO" Then
      getWWWAuthConfig();
     
      If %SignonUserId = &defaultUserId Then
         &user = Upper(%Request.GetHeader("uid"));
         If &user <> "" Then
           
            SetAuthenticationResult( True, Upper(&user), "", False);
            Return;
         End-If;
 End-Function;

4. Finding the Default Profile for ps site

 Run the following command to find the configuration.properties file.

locate configuration.properties

After running the above command properties file located in the following location.

/home/psadm2/psft/pt/8.53/webserv/peoplesoft/applications/peoplesoft/PORTAL.war/WEB-INF/psftdocs/ps/configuration.properties

edit the configuration.properties and search the WebProfile= string and it will fine the default profile for the ps site. In my example

WebProfile=PROD


5. Configuring the Shibboleth People Code

  5.1 Create the People Soft User
   Navigate the Main Menu --> People Tools --> Security --> User Profiles --> User Profile.
   
   Click Add New Value Button and Enter User ID is PUBUSER and Click Add Button. Please enter the following details in the General and ID tab after Clicking the Add button.

General Tab


Choose Symbolic ID in the combo box. The symbolic ID is sysadm1.
Enter Password, Confirm Password, and User Id Alias

ID Tab

Choose the Id Type is None.

Click Save Button and It will create the user without roles and permissions.

 5.2 Modify the Web Profile

  Navigate to Main Menu --> People Toos --> Web Profile --> and Web Profile Configuration.

Enter the profile name is PROD and you found in the profile name in the configuration.properties file.

After Clicking the Search button and it will take you the PROD web profile configuration page. Click the Security tab in the Web Profile Configuration page and modify the following properties to enable the SSO.

Enter Days to Auto fill User ID is zero

Public Users:

Select Allow Public Access Check Box
Enter User ID and Password

Click the Save Button and it will save the modified configuration.


 5.3 Modify the Sign On Code


  Navigate the Main Menu --> People Tools --> Security --> Security Objects --> Sign On People Code. Perform the following task to enable the SSO.

Unckeck All Exec Auth Fail check Boxes.

Modify the WWW_AUTHENTICATION function record definition Name and leave remaining as it is

After modifying the Sign On People Code look Like this.





 

5.4 Restart the Weblogic Server

6. Testing the Single Signon from Shibboleth To People Soft


Open the Browser and enter the following url

https://<Service Provider Host Name>/psp/ps/EMPLOYEE/HRMS/h/?tab=DEFAULT

After entering the Protected URL in the browser and it will redirect to IDP login Page and shown below.






Enter User Name and Password and Click Login Button and It will redirect to People Soft Default Administration Page and the screen shot shown below.






Installing and Configuring the Apache Web Logic Plugin

Installing and Configuring the Apache Web Logic Plugin 64 Bit

Pre-Requisite
1. Download the Oracle Apache Web Logic Plugin
2. Configure SSL for Web Logic
3. Get the Root CA from the Certificate Authority
4. Install the Java and Export the JAVA_HOME as environment variables.
 
Configuration

1. Extract WebLogic Apache Plugin Zip File
 
 In the plugin zip bundle and choose the right version of apache plugin zip file and extract the zip file. In my example apache version is 2.2 64 bit and the extract zip file name is WLSPlugin11g-64bit-Apache2.2-linux64-x86_64.zip file. After Extracting the zip file and the WLS Plugin Directory Structure look like this.

   

 

2. Exporting the LD_LIBRARY_PATH

Login as a root or sudo user and Go to the /etc directory and edit the profile directory and add the LD_LIBARY_PATH at the end of the file.

LD_LIBRARY_PATH="/opt/shibboleth-sp/lib:/etc/httpd/modules:/root/soft/wls/lib"
export LD_LIBRARY_PATH


In the above configuration, I have highlighted the weblogic apache plugin lib directory location where my plugin lib directory resides.

3. Configuring the Web Logic Wallet

Go to the Weblogic Plugin Extracted Directory  and perform the following configuration tasks to create the wallet and add the root certificate to the wallet.
 
 3.1 Creating the Web Logic Wallet

 Run the following command to create the wallet.
 
 ./bin/orapki wallet create -wallet my-wallet -auto_login_only
 

After running the command and it will create the my-wallet directory and also it create the cwallet.sso file inside the my-wallet directory.
 
 3.2 Add the Root CA to the

 Run the following command to add the root certificate into the my-wallet.

 ./bin/orapki wallet add -wallet my-wallet -trusted_cert -cert ca.crt -auto_login_only

In the above configuration, the root ca certificate is ca.crt. If you already configure the ssl for web logic and the root certificate is available in the trusted store.
4. Configure the weblogic.config file

Go to the Weblogic Plugin Extracted Directory  and create the wls.config file and perform the following task to configure the weblogic plugin.

4.1 Load the Web Logic Module
 LoadModule weblogic_module <Web Logic Module File.sso>






4.2 Configure the Web Logic Plugin If Module

Add the following content into the file and turn on the SecureProxy and Specify the wallet location

 <IfModule mod_weblogic.c>

    Debug ALL
    DebugConfigInfo On
    WLLogFile /tmp/wl-proxy.log
    KeepAliveEnabled ON
    SecureProxy ON    WLSSLWallet <Web Logic Wallet Location>
 

 </IfModule>


4.3 Configure the Apache routing to Web Logic

  <Location / >
    SetHandler weblogic-handler
    WebLogicHost <Web Logic Host>
    WebLogicPort <WebLogic SSL Port>
  </Location>


   Configure the Host and Web Logic SSL Port.

4.4 Sample wls.config File 

After configuring the wls.config file as follows.

 LoadModule weblogic_module /root/soft/wls/lib/mod_wl.so
 <IfModule mod_weblogic.c>

    Debug ALL
    DebugConfigInfo On
    WLLogFile /tmp/wl-proxy.log
    KeepAliveEnabled ON
    SecureProxy ON
    WLSSLWallet /root/soft/wls/my-wallet
</IfModule>

<Location / >
    SetHandler weblogic-handler
    WebLogicHost 192.168.56.101
    WebLogicPort 4430
 </Location>

5. Including wls.config file in httpd.conf file

Login as a root and modify the httpd.conf file in the /ete/httpd/conf directory. Add the following content in the Include section in the httpd.conf file.

Include /root/soft/wls/wls.config

In the above configuration, /root/soft/wls/wls.config is my sample wls.conf file. Please replace with your sample config file location.

6. Restart the Apache Server

service httpd restart

7. Enabling the Web Logic Plugin in the Weblogic Admin Console 

Login to the Web Logic Admin Console and navigate the following location and Enable the Web Logic Plugin

7.1 Click Lock and Edit button to modify the weblogic configuration
7.2 Navigate the Environment --> Servers and It will display the following screen.




My Server Name is PIA(admin). Click the PIA(admin) Server and It will display the following screen.



 



Click the Advanced Button and Enable the WebLogic Plug-In Enabled check box. After enable the WebLogic Plug-In Enabled check box and the screen should like this.







Click Save Button and Restart the Web Logic Server to effect the changes.

8. Testing the Web Logic Apache Plugin

Open the browser and enter the https://<HostName>/console in the URL. In my example my url is https://pspt.liyaqat.com/console/. After entering the url and it will display the following screen.






9. Common Errors

Problem: mod_weblogic(ssl): Cannot Load library: libwlssl.so


Cause: The weblogic apache plugin lib directory not available in the LD_LIBRARY_PATH

Solution:

9.1 Go to the /etc/ directory and edit the profile file. Add the LD_LIBRARY_PATH path variable and Export the LD_LIBRARY_PATH of the weblogic apache plugin lib directory and restart the apache web server

9.2 Some times LD_LIBRARY_PATH not able to visible to your apache web server. Please add the LD_LIBRARY_PATH in the following location to load the LD_LIBRARY_PATH.

Go to the /etc/init.d directory and edit the functions file and add the LD_LIBRARY_PATH into the functions file.

The Sample LD_LIBRARY_PATH as follows.

export LD_LIBRARY_PATH=/opt/shibboleth-sp/lib:/etc/httpd/modules:/root/soft/wls/lib

The highlighted the weblogic plugin library directory

Restart the Apache Web Server and the issue will be resolved.
 

 

Thursday, May 2, 2013

Service Provider Registering with Identity Provider

Login as a root or sudo user to configure the Service Provider Registration with Identity Provider as follows.

Service Provider Configuration


1. Protecting the Resource

 Go to the /etc/httpd/conf.d directory and edit the shib.conf file and add the following content.

<Location /testapp>
  AuthType shibboleth
  ShibRequireSession On
  require shibboleth
  ShibUseHeaders On
</Location>

/testapp is my protected resource. The testapp is deployed in the tomcat6 and deployment steps are configured my previous blog. Please follow the lync and configure the testapp war file.

TESTAPP WAR FILE

2. Configuring  AJP protocol request transfer from Httpd to Tomcat6

Go to the /etc/httpd/conf.d directory and create the proxy_ajp.conf file and the following content.

ProxyPass /testapp/ ajp://127.0.0.1:8009/testapp/

3. Test the Apache Server Configuration

Run the apachectl -t command. If any error found in the configuration file, please fix the configuration, and retry again.

4.Configuring the SAML Response Attributes

Go to the /etc/shibboleth/ directory and edit the attribute-map.xml file and the following attribute definition or uncomment attribute definition. They are

        <Attribute name="urn:oid:0.9.2342.19200300.100.1.1" id="uid"/>
        <Attribute name="urn:oid:2.5.4.4" id="sn"/>
        <Attribute name="urn:oid:2.5.4.42" id="givenName"/>

4. Configure Attribute - Policy

If you want to include or exclude, please modify the attribute-policy.xml file. I am using the default configuration attribute-policy File.

5. Test the shibboleth configuration

shibd -t

The following output display after running the above command

6. Restart httpd, and shibd services

service httpd restart
service shibd restart

7. Logs

Please check any errors found in the shib logs or httpd log

Shibd Logs

The shibboleth log files are available in the /var/log/shibboleth and the log file name is shibd.log. After starting the server without any issue, the log file look like this.





Httpd Log


The Apache Server log files are available in the /etc/httpd/logs


>>Follow Continuation

Service Provider Registering with Identity Provider Configuration Continuation

Identity Provider Configuration

Login as a root or sudo user to configure the identity provider attributes.

1. Configure attribute-resolver.xml

Go to the /opt/shibboleth-idp/conf directory and edit the attribute-resolver.xml file.

1.1 Define LDAP Connector Configuration

Uncomment the <resolver:DataConnector and modify the configuration as per your environment.

<resolver:DataConnector id="myLDAP" xsi:type="dc:LDAPDirectory"
        ldapURL="ldap://<Ldap Host Name>"
        baseDN="ou=people,dc=liyaqat,dc=com"
        principal="cn=Manager,dc=liyaqat,dc=com"
        principalCredential="<Password>">
        <dc:FilterTemplate>
            <![CDATA[
                (uid=$requestContext.principalName)
            ]]>
        </dc:FilterTemplate>
    </resolver:DataConnector>

1.2 Define the Target ID

    <resolver:DataConnector xsi:type="dc:ComputedId"
                            id="computedID"
                            generatedAttributeID="computedID"
                            sourceAttributeID="uid"
                            salt="your random string here">
        <resolver:Dependency ref="myLDAP" />
    </resolver:DataConnector>

1.3 Defining the attribute

Uncomment the sn,givenname,uid attrubutes.

 The attribute-resolver.xml file configuration completed.

2. Configure attribute-filter.xml

Go to the /opt/shibboleth-idp/conf directory and edit the attribute-filter.xml file.

 2.1 Defining the Attribute Filter Policy for specific Service Provider

We are releasing the uid, givenName, and surname. These attributes are configured in the attribute-filter.xml file.

<afp:AttributeFilterPolicy>
        <afp:PolicyRequirementRule xsi:type="basic:AttributeRequesterString" value="https://<Service Provider Host Name>/shibboleth" />

        <afp:AttributeRule attributeID="givenName">
            <afp:PermitValueRule xsi:type="basic:ANY" />
        </afp:AttributeRule>
        <afp:AttributeRule attributeID="uid">
            <afp:PermitValueRule xsi:type="basic:ANY"/>
        </afp:AttributeRule>
        <afp:AttributeRule attributeID="surname">
            <afp:PermitValueRule xsi:type="basic:ANY"/>
        </afp:AttributeRule>
   </afp:AttributeFilterPolicy>

3. Configure relying-party.xml

Go to the /opt/shibboleth-idp/conf directory and edit the relying-party.xml file.

3.1 Download the Service Provider Metadata

 Replace the service provider host with your host name and paste the url into the browser. It will ask to save the file and save the file in /tmp directory and copy the sp metadata file to /opt/shibboleth-idp/metadata directory.

https://<Service Provider Host>/Shibboleth.sso/Metadata. For example the metadata url is https://sp.liyaqat.com/Shibboleth.sso/Metadata

3.2 Configure the Metada in relying-party.xml file

Edit the relying-party.xml file and search the MetadataProvider and add the following content under metadata section.

<metadata:MetadataProvider id="sp.liyaqat.com" xsi:type="metadata:FilesystemMetadataProvider"
                          metadataFile="/opt/shibboleth-idp/metadata/sp-liyaqat-com-metadata.xml"/>


Configure the id and metadataFile location. I have highlighted configuration details in red colour.

4. Restarting the IDP Server

Run the following commands to restart the apache web server and tomcat server.

service httpd restart
service tomcat6 restart

5. Testing the Relying Party Configuration

Go to the /opt/shibboleth-idp/bin directory and run the aacli.sh command and it will display the SAML response attribute to sending from idp to SP.

 ./aacli.sh --configDir=../conf --principal=<userName> --requester=https://<Service Provider Host Name>/shibboleth

The example principal is liyaqat and service provider host name is sp.liyaqat.com

After running the above command and it will display the saml response attribute releasing from IDP to Shibboleth SP. The Sample is given below.

<?xml version="1.0" encoding="UTF-8"?><saml2:AttributeStatement xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
   <saml2:Attribute FriendlyName="uid" Name="urn:oid:0.9.2342.19200300.100.1.1" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
      <saml2:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">liyaqat</saml2:AttributeValue>
   </saml2:Attribute>
   <saml2:Attribute FriendlyName="sn" Name="urn:oid:2.5.4.4" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
      <saml2:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">sahull</saml2:AttributeValue>
   </saml2:Attribute>
   <saml2:Attribute FriendlyName="givenName" Name="urn:oid:2.5.4.42" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
      <saml2:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">liyaqat</saml2:AttributeValue>
   </saml2:Attribute>
</saml2:AttributeStatement>


>>Follow the Testing Shibboleth Sp Registering with IDP

Service Provider Registering with Identity Provider Configuration Testing

Service Provider Registering with Identity Provider Configuration Testing

1. Enter the Protected Page URL

 https://<Service Provider Host>/testapp/. The Service Provider Host Name is sp.liyaqat.com

After entering the protected resource in the url and it will redirect to idp login page as shown as a screen shot.



2. Submit Login Page

Enter user name and password, Click Login button and it will display the protected page with header content as shown below.







Please observe at the end of the page, we have requested three attributes, uid, givenName, sn. In the header.jsp file uid=liyaqat, givenName=liyaqat, sn=sahull and REMOTE_USER=liyaqat.

All the best for your Shibboleth installation and configuration.

References

Shibboleth Wiki Page

Installation and Configuration of Tomcat 6

Installation and Configuration of Tomcat 6

Install Tomcat6

Login as root or sudo user, please install the tomcat 6 as follows.

yum install tomcat6

Generate the Self Signed Certificate

Go to the /etc/tomcat6 directory and run the following command to create the self signed certificate. Please make sure that open jdk installed and keytool in the path.

keytool -genkeypair -keystore sp.jks -alias tomcat

After entering the above command, it will ask the keystore password, First and Last Name is your machine name , and key pass. Please ignore remaining attribute.

Enable the SSL for tomcat6

Go to the /etc/tomcat6 directory and edit the server.xml and uncomment the Connector port 8443. After uncommented, the connector configuration as follows.

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               keystoreFile="/etc/tomcat6/sp.jks" keystorePass="<Key Store Password>"
               />

I have highlighted in red colour to configure key store location and key store password.  


Deploy the Sample Web Application

I have developed the sample web application and it contains the header.jsp file and it will display all the headers from the request. This web application is deployed in the tomcat6. The deployment shown below.

Go to the /etc/tomcat6/Catalina/localhost/ directory and create the testapp.xml file and add the following content to deploy the testapp war file into the tomcat.

<Context docBase="/tmp/testapp.war"
        privileged="true"
        antiResourceLocking="false"
        antiJARLocking="false"
        unpackWAR="true"
        swallowOutput="true" />

Restart the Tomcat6

service tomcat6 restart

Log File Location

The tomcat6 log files are available in the /var/log/tomcat6/ directory.


Service Provider Static IP and Fire Wall Configuration

Service Provider Static IP Configuration

I have already posted in the my previous blog to configure static IP. Please follow the lync and configure the static IP.

Static IP Configuration

Fire Wall Configuration

Inbound connection port 443 needs to be configured to every one. Go to the /etc/sysconfig directory and edit the iptables file and add the following content

-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT

Add the IP Address and in the Hosts Entry File
       
GO to the /etc/ directory and edit the hosts file. Add the following content to resolve the host name while accessing through host name.

     192.168.252.150 <IDP Host Name>.

      The Sample Configuration is
   
     192.168.252.150 idp.liyaqat.com


Restart the IP tables

service iptables restart

After restarting the service, the following output shown in the command line.





Follow SP Registering with IDP

Wednesday, May 1, 2013

Shibboleth Service Provider Configuration

Shibboleth Service Provider Configuration

Login as a root or Sudo user and configure the service provider. After installing the service provider, the config files are available in the /etc/shibboleth directory.

Copy IDP Metadata

Copy the idp-metada.xml from the identity provider server location. The default location from the idp server is /opt/shibboleth-idp/metadata/idp-metada.xml

Configure the shibboleth2.xml file

Go to the /etc/shibboleth directory and edit the shibboleth2.xml file.

Configure the entityID

<ApplicationDefaults entityID="https://<Service Provider Host Name>/shibboleth" REMOTE_USER="<Unique ID>">
The unique id is uid or samAccountName. This attribute is available in the SAML response.

Configure SSO

<SSO entityID="https://<Idp Host Name>/idp/shibboleth"
                 discoveryProtocol="SAMLDS" discoveryURL="https://<Idp Host Name>/DS/WAYF">
              SAML2 SAML1
 </SSO>

Configure Status Handler

By default Status handler is invoked from the browser using local ip address. If you want to invoke based on the static IP, Please add the static ip in acl attribute.

<Handler type="Status" Location="/Status" acl="127.0.0.1 192.168.252.151"/>

I have added my sp static IP in the  acl attribute. The ip address is 192.168.252.151.

Configure Session Handler

By default showAttributeValues value is false. If you want to see the session attributes in the runtime, please enable from false to true value.

<Handler type="Session" Location="/Session" showAttributeValues="true"/>

Configure the IDP Metadata

 Replace with your IDP Host name and Specify the IDP metada xml file name in the backingFilePath attribute


        <MetadataProvider type="XML" uri="https://<IDP Host Name>/idp/profile/Metadata/SAML"
              backingFilePath="idp-metadata.xml" reloadInterval="7200">
        </MetadataProvider>

Configure the Certificate Key and Cert File

By default Self Signed certicate is created after installing the service provider. If you want to modify the self signed certificate with signed certificate, please modify key and certicate files. If you don't want to modify leave as it is.

<CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>


Shibboleth2.xml configuration completed.

Export LD_LIBRARY_PATH

By default shibboleth library files are not available in the LD_LIBRARY_PATH.  This LD_LIBRARY_PATH is required to test our configuration files are accurate or any error.

export LD_LIBRARY_PATH=/opt/shibboleth/lib64:$LD_LIBRARY_PATH


Disable the Suse Linux Firewall.

By default Suselinux fire wall is enforced. The shibboleth Unix Listener throws exception after starting the shibboleth server and you can not access the /Status page. Run the setenforce 0 to disable the suse linux firewall and It will disable the firewall temporarily. If you want to disable the permanently as follows.

Edit the /etc/sysconfig/selinux file and modify from SELINUX=enforcing to SELINUX=disabled.


Testing the Shibboleth Configuration

[root@sp shibboleth]# shibd -t
overall configuration is loadable, check console for non-fatal problems

If your not able to see above message, please fix the errors and try the above command.

Restarting Shibboleth SP

service shibd restart


Testing the Shibboleth Installation

Open the Browser and paste the following url to verify our installation and configuration is success or failure

https://127.0.0.1/Shibboleth.sso/Status


If you see the Session Status Handler Page, Your Installation and confugurations are correct. Your not able to see the Status Page, Please trouble shoot as follows.

1) Check whether your disable suselinu firewall.
2) Check whether your setup LD_LIBRARY_PATH
3) Check more info in the log.


Log Files Location

 /var/log/shibboleth/shibd.log
 /var/log/shibboleth/shibd_warn.log
 /var/log/shibboleth/transaction.log
 /var/log/shibboleth/signature.log


>>Follow the Static IP and Firewall Configuration
 

Shibboleth Service Provider Apache Configuration

Shibboleth Service Provider Apache Configuration

Login as a root or sudo user and modify the httpd.conf and ssl.conf file.

Modify httpd.conf file

Go to the /etc/conf/ directory and edit the httpd.conf file. Modify the following parameters.
UseCanonicalName  On
ServerName  <host.domainName>. For example service provider domain name is sp.liyaqat.com
 
Modify the ssl.conf file

By default SSL is enabled after installing the mod_ssl. If you want to change self signed certificate to Signed Certificate. Please modify the following parameters in the /etc/httpd/conf.d/ssl.conf file.  

SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

Testing the Configuration

Run the apachectl -t command and it will verify the configuration changes and it will give the results. If you found any error while running the apachectl -t command, please fix the errors and retry until it comes Syntax OK

Restart the Apache Server

Run the service httpd restart command and it will restart the apache httpd server.

Log Files Location

The log files are available in the /etc/httpd/logs/ directory.


>>Follow the Shibboleth Service Provider Configuration

Shibboleth Service Provider Installation

Service Provider Installation

Software Requirement
       Cent OS 6.4 64 Bit
       Tomcat6
       Apache 2.2 Web Server
       mod_ssl
       shibboleth.x86_64
       Java 1.6

      
      
Install the Cent OS 6.4 64 Bit in Virtual Machines.
     Please follow the Cent OS Install Lync to install the centos.

Install the following software login as a root or sudo user.

Install Tomcat6, httpd, mod_ssl,  and open jdk from the centos default repositories.
    yum install tomcat6
    yum install httpd
    yum install mod_ssl
    yum install java-1.6.0-openjdk-devel.x86_64


Install Shibboleth Service Provider


Go to the /etc/yum.repos.d directory and run the following command to download the security:shibboleth.repo file.

wget http://download.opensuse.org/repositories/security://shibboleth/CentOS_CentOS-6/security:shibboleth.repo

Run the following command to install the shibboleth service provider
yum install shibboleth.x86_64

>>Follow Shibboleth Apache Server Configuration


Office 365 OAuth 2.0 Test Client Setup


OAuth 2.0 Assertion Flow with Office 365 Authorization Server

Pr-Requisite Software
  •  Download Gradle Software
 Gradle All
  •  Setup Environment Variable and Path
           Define GRADLE_HOME Directory
           Setup the PATH for gradle. For Example
           Set GRADLE_HOME=c:\Gradle-1.5
           Set PATH= %GRADLE_HOME%\bin;%PATH%
           Set the Java Home Directory. For example set JAVA_HOME="c:\Progra~1\Java\jdk1.6.0_31".
  •  Creating the New App Principal Name

Build the Gradle Build File (build.gradle)
    apply plugin : 'java'
    apply plugin : 'eclipse'
    apply plugin : 'application'
    sourceCompatibility = 1.6
    group = 'oauth.sample.office365.client'
    version = '1.0'
    repositories {
          mavenCentral()
    }
   
    dependencies{
                compile 'org.apache.httpcomponents:httpclient:4.2.2','com.google.code.gson:gson:2.2.2','org.slf4j:log4j-over-slf4j:1.7.5'
    }


Create a Eclipse Project Directory
       Open a Command Prompt and create a following directory structure in c drive in windows or else unix. For unix use forward slash instead of back slash
       mkdir oauth
       mkdir oauth\office365oauth
       mkdir oauth\office365oauth\src
       mkdir oauth\office365oauth\src\main
       mkdir oauth\office365oauth\src\main\java
       mkdir oauth\office365oauth\src\main\resources

      Copy the gradle.build file to c:\oauth\office365oauth
      Execute the gradle cleanEclipse eclipse command and it will create the eclipse project.                 
Import the Project into the Eclipse
         Open th eclipse. Click File --> Import --> General --> Existing Project into Workspace --> Next. It will display the Following Screen.

'
 Click Brose Button And Choose the Eclipse Project Directory. In Our Case C:\oauth\Office365oauth project

 After Choosing the Eclipse Project, Please Click Ok Button and it will display the following screen.

 Click Finish button and It will Import the eclipse project into the workspace. The sample imported eclipse screen shot given below.



       
Build the Test Client for Oauth 2.0
Build the OAuth Test Client Devided into 2 parts.  They are
 a. Build Assertion
 b. Send Request to Authorization Server to Get The Access Token
                
 Build Assertion

 Assertion need to be encoded with base64 format. The following sequence build the assertion. They are
   
Building Assertion Header
  The assertion header parameters are typ and alg. The typ is Header type is JWT (JSON Web Token) and alg is algorithm is HS256 (Hash Sha 256). The Sample Code is given below.

  Map <String,String> header= new HashMap<String,String>()
  header.put("typ","JWT");
  header.put("alg","HS256");
     
Convert the Assertion Header to JSON Object            

 String strHeader==gson.toJson(header);

Convert the JSON Object to Encode Base 64 Object
String strEnodeHeader=Base64.encodeBase64String(strHeader.getBytes("UTF8"));
Assertion Header Completed. Next Build the Assertion Pay Load.
Build Assertion Pay Load
 The assertion payload parameters are iss, aud, nbf, and exp. 
 The iss is issuer. The issuer is the application principal id @ Microsoft Office 365 Tenant.
 The aud is audience and the format of the aud is URI. The Sample aud is ACS Principal ID / Authorization   Host @  Microsoft Office 365 Tenant. 
 The nbf is Not Before. The sample value is Current Date in seconds.
 The exp is expired. The expiration of Access Token is in seconds.
 The Sample code of the PayLoad is given below.

   Map<String,String> payload= new HashMap<String,String>();
   payload.put("iss",AppPrincipalName+"@"+"Microsoft Office 365 Tenant Name");
   payload.put("aud",ACSPrincipalID+"/"+"Authorizer Server Host"+"@"+"Microsoft Office 365 Tenant Name");
   payload.put("nbf",""+(new Date().getTime()/1000));
   payload.put("exp",""+(addSecondsToCurrentTime(3600).getTime()/1000));

Convert the PayLoad Object to JSon Object
  
  String strPayLoad= gson.toJson(payload);
Encode PayLoad JSON Obectwith Base 64
 String strEnodepayLoad=Base64.encodeBase64String(strPayLoad.getBytes("UTF8"));
Assertion Pay Load Completed. Next Combine the Assertion Header Encode with Assertion Payload Encode

Append Assertion Header Encode with Assertion Payload Encode
 As per the JWT specification the assertion encode header and assertion payload header append with dot. The Code is given below.

 String rawToken=  strEnodeHeader + "." +strPayLoad;

Sign the Raw Token                 

As per the the JWT specification, the raw token need to be signed with HmacSHA256 with secret key of the Application user Principal Name. This secret key is generated while creating the application principal name using the power shell. The sample Code is given below.

SecretKeySpec secretKey = null;

secretKey = new SecretKeySpec(Base64.decodeBase64(signingKey), "HmacSHA256");
Mac mac;

byte[] signedData = null;

try{

  mac = Mac.getInstance("HmacSHA256");
  mac.init(secretKey);
  mac.update(rawToken.getBytes("UTF-8"));
  signedData = mac.doFinal();

}

 catch (Exception e) {
            e.printStackTrace();

}
       

Build The Signature

As per the JWT specification, the signed token needs to be encoded with base 64. The sample Code is given below

 String signature = Base64.encodeBase64String(signedData);

Encode Signatre and RawToken

As per the JWT specification the raw token and signature append with dot and encode with base64 format. The Code is given below.

 String assertion = String.format("%s.%s", rawToken, signature);

Assertion Building Completed.

Send Request to Authorization Server to Get The Access Token

 Build the Post Request

  The Authorization server url is required to construct the pst request. The sample code is given below.

DefaultHttpClient client= new DefaultHttpClient();
HttpPost post= new HttpPost("https://accounts.accesscontrol.windows.net/tokens/OAuth/2");
List <NameValuePair> nvps = new ArrayList<NameValuePair>();

 Add the Request Parameters to the Post Request
 The resource format is uri and Protected Resource Principal Id is 00000002-0000-0000-c000-000000000000 / Protected Resource Host Name is graph.windows.net @ Microsoft Office 365 Tenant.

 String resource=String.format("%s/%s@%s", "00000002-0000-0000-c000-000000000000", "graph.windows.net","Microsoft Tenant Name");
 nvps.add(new BasicNameValuePair("grant_type", "http://oauth.net/grant_type/jwt/1.0/bearer"));
 nvps.add(new BasicNameValuePair("assertion", assertion));
 nvps.add(new BasicNameValuePair("resource", resource));


Send Post Request

post.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
HttpResponse response=client.execute(post); 


Extract the Response


if(response.getStatusLine().getStatusCode() == 200){

  HttpEntity entity=response.getEntity();
  if (entity != null)

 { 
   String retresponse=handler.handleResponse(response);
   The response format is JSON and response attributes are token_type, access_token, expires_in, not_before, expires_on, resource
 
 }     
  
Example Code

package oauth.sample.office365.client;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import oauth.sample.office365.OauthToken;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class TestOAuthClient 
{
    private static String ALGORITHM="HS256";
    private static String TYPE="JWT";
    private static String APP_PRINCIPAL_ID="<Replace with App Service Principal ID>";
    private static String ACS_PRINCIPAL_ID="00000001-0000-0000-c000-000000000000";
    private static String AUTHRIZER_SERVER_HOST="accounts.accesscontrol.windows.net";

   private static String DOMAIN_CONTEXT_ID="Replace with MicroSoft Office 365 Tenant Name";
    private static String SYMMETRIC_KEY="Replace with Secret Key";
    private static String AUTHRIZER_SERVER_URL="https://accounts.accesscontrol.windows.net/tokens/OAuth/2";
    private static String GRANT_TYPE_URL="http://oauth.net/grant_type/jwt/1.0/bearer";
    private static String PROTECTED_RESOURCE_PRINCIPAL_ID="00000002-0000-0000-c000-000000000000";
    private static String PROTECTED_RES_HOST_NAME="graph.windows.net";
    
    private static Gson gson= new Gson();
    public TestOAuthClient() {
        // TODO Auto-generated constructor stub
    }
    
    public static void main(String args[]) throws Exception
    {
        
        String assertion=buildAssertion();
        
        // Initializing the Http Connection
        DefaultHttpClient client= new DefaultHttpClient();
        HttpPost post= new HttpPost(AUTHRIZER_SERVER_URL);
        List <NameValuePair> nvps = new ArrayList<NameValuePair>();
        
        String resource=String.format("%s/%s@%s", PROTECTED_RESOURCE_PRINCIPAL_ID, PROTECTED_RES_HOST_NAME,DOMAIN_CONTEXT_ID);
        
        nvps.add(new BasicNameValuePair("grant_type", GRANT_TYPE_URL));
        nvps.add(new BasicNameValuePair("assertion", assertion));
        nvps.add(new BasicNameValuePair("resource", resource));
        
        post.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
        
        HttpResponse response=client.execute(post);
        
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println(response.getProtocolVersion());

        if(response.getStatusLine().getStatusCode() == 200)
        {
            diplayHeaders(response,"authenticate");
            HttpEntity entity=response.getEntity();
            if (entity != null) {
                
                System.out.println("Response content length: " + entity.getContentLength());
                BasicResponseHandler handler= new BasicResponseHandler();
                String retresponse=handler.handleResponse(response);
                
                OauthToken token =gson.fromJson(retresponse, OauthToken.class);
                
                System.out.println(retresponse);
                
                System.out.println("Exire On " +token.getExpires_on());
                System.out.println("Exire in " +token.getExpires_in());
                System.out.println("Exire not Before " +new Date(token.getNot_before()*1000));
                System.out.println("Current Time " +new Date().getTime());
                
                System.out.println("Expire Date "+ addSecondsToCurrentTime((int)token.getExpires_in()) + "  - "+token.getExpires_on());
                
                
                EntityUtils.consume(entity);
            }
        }
        else
        {
            diplayHeaders(response,"authenticate");
          
            //throw new Office365Exception("Authentication Token Generation Error "+config.getAuthUrl());
        }
    }
    
    public static void diplayHeaders(HttpResponse response,String methodName)
    {
        Header headers[]= response.getAllHeaders();
        for (Header header : headers) 
        {
            System.out.println(methodName+ " - Headers  - "+header.getName() + "  -  "+header.getValue());
        }
    }

    
    public static String buildAssertion()
    {
        String result="";
        // start Assertion
        
        
        // Building Header
        
        Map<String, String> headerMap= new HashMap<String, String>();
        headerMap.put("alg", ALGORITHM);
        headerMap.put("typ", TYPE);
        
        String strHeader=buildStringFromMap(headerMap);
        System.out.println(strHeader);
        
        Map<String, String> body= new HashMap<String,String>();
        //format App Principal ID @ Domain Context ID
        
        body.put("iss", APP_PRINCIPAL_ID+"@"+DOMAIN_CONTEXT_ID);
        // Format ACS Principal Name / Authentication Host @ Domain Context ID 
        body.put("aud", ACS_PRINCIPAL_ID+"/"+AUTHRIZER_SERVER_HOST+"@"+DOMAIN_CONTEXT_ID);
        body.put("nbf", ""+(new Date().getTime()/1000));
        body.put("exp", ""+(addSecondsToCurrentTime(3600).getTime()/1000));
        String strBody=buildStringFromMap(body);
        System.out.println(strBody);
        // Building Raw Token header + "." + Body
        String rawToken= strHeader + "."+ strBody;
        
        // sign the data using symmetric Key
        
        byte signedBytes[]= signData(SYMMETRIC_KEY, rawToken);
        
        //Create the Signature
        
        String signature = Base64.encodeBase64String(signedBytes);
        
        // Build the Access Token  format is rawToken +"."+signature
        
        result = String.format("%s.%s", rawToken, signature);
        
        // End Assertion
        
        
        
        System.out.println(strHeader);
        
        
        
        return result;
    }
    

    private static byte[] signData(String signingKey, String rawToken)  
    {
        SecretKeySpec secretKey = null;
        System.out.println("Finding Decode Key "+new String(Base64.decodeBase64(signingKey)));
        secretKey = new SecretKeySpec(Base64.decodeBase64(signingKey), "HmacSHA256");
        Mac mac;
        byte[] signedData = null;
        try
        {
            mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKey);
            mac.update(rawToken.getBytes("UTF-8"));
            signedData = mac.doFinal();
        } catch (Exception e) {
            e.printStackTrace();
        }        
        return signedData;
    }
    
    
    public static String buildStringFromMap(Map<String, String> data)
    {
        String result="";
        if(!data.isEmpty())
        {
            result=gson.toJson(data);
            try {
                result=Base64.encodeBase64String(result.getBytes("UTF8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Date addSecondsToCurrentTime(int seconds) 
    {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        System.out.println(calendar.getTime());
        calendar.add(Calendar.SECOND, seconds);
        
        return calendar.getTime();
    }

}






package oauth.sample.office365;

public class OauthToken 
{
    private String token_type;
    private String access_token;
    private long expires_in;
    private long not_before;
    private long expires_on;
    private String resource;
    
    
    public String getToken_type() {
        return token_type;
    }


    public void setToken_type(String token_type) {
        this.token_type = token_type;
    }


    public String getAccess_token() {
        return access_token;
    }


    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }


    public long getExpires_in() {
        return expires_in;
    }


    public void setExpires_in(long expires_in) {
        this.expires_in = expires_in;
    }


    public long getNot_before() {
        return not_before;
    }


    public void setNot_before(long not_before) {
        this.not_before = not_before;
    }


    public long getExpires_on() {
        return expires_on;
    }


    public void setExpires_on(long expires_on) {
        this.expires_on = expires_on;
    }


    public String getResource() {
        return resource;
    }


    public void setResource(String resource) {
        this.resource = resource;
    }


    public OauthToken() {
        // TODO Auto-generated constructor stub
    }

}
 



Compile the Code 

 Go to the Eclipse Project Directory command Prompt and run the gradle build command and It will compile. The compilation output as follows


C:\oauth\office365oauth>gradle build
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:assemble UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build UP-TO-DATE

BUILD SUCCESSFUL



Execute the Test Client
Add the following content at the end of the line in the build.gradle file.

mainClassName="oauth.sample.office365.client.TestOAuthClient"


After Adding the above content , the build file shown like this.



apply plugin : 'java'
apply plugin : 'eclipse'
apply plugin : 'application'

sourceCompatibility = 1.6
group = 'oauth.sample.office365.client'
version = '1.0'
repositories {
 mavenCentral()
}
dependencies{
    compile "org.apache.httpcomponents:httpclient:4.2.2",
    "com.google.code.gson:gson:2.2.2",
    "org.slf4j:log4j-over-slf4j:1.7.5"
}
mainClassName="oauth.sample.office365.client.TestOAuthClient" 



After running the gradle run command the following output is shown.


C:\oauth\office365oauth>gradle run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Wed May 01 18:33:17 PDT 2013
eyJleHAiOiIxMzY3NDYxOTk3IiwibmJmIjoiMTM2NzQ1ODM5NyIsImF1ZCI6IjAwMDAwMDAxLTAwMDAtMDAwMC1jMDAwLTAwMDAwMDAwMDAwMC9hY2NvdW50cy5hY2Nlc3Njb250cm9s
LndpbmRvd3MubmV0QHNmc3VvZmZpY2UzNjVkZXYub25taWNyb3NvZnQuY29tIiwiaXNzIjoiNGU5MGNmNDItNmM2MC00NzA2LTg1MDktZTM5YzM3NjViYzExQHNmc3VvZmZpY2UzNjVk
ZXYub25taWNyb3NvZnQuY29tIn0=
Finding Decode Key ò╟P↔°?Θ╣■:/£ôm┼zÖ6*9?←≥≥Q§←££0
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
----------------------------------------
HTTP/1.1 200 OK
HTTP/1.1
authenticate - Headers  - Cache-Control  -  no-cache, no-store
authenticate - Headers  - Pragma  -  no-cache
authenticate - Headers  - Content-Type  -  application/json; charset=utf-8
authenticate - Headers  - Expires  -  -1
authenticate - Headers  - request-id  -  9ee87462-e08d-4ad2-af7a-2c50f47b6346
authenticate - Headers  - X-Content-Type-Options  -  nosniff
authenticate - Headers  - Date  -  Thu, 02 May 2013 01:34:14 GMT
authenticate - Headers  - Content-Length  -  1218
Response content length: 1218
{"token_type":"Bearer","access_token":"Access Token with Encoded string","expires_in":"43200","not_before":"1367458455","expires_on":"1367501655","resour
ce":"00000002-0000-0000-c000-000000000000/graph.windows.net@Microsoft Tenant ID"}
Exire On 1367501655
Exire in 43200
Exire not Before Wed May 01 18:34:15 PDT 2013
Current Time 1367458399228
Wed May 01 18:33:19 PDT 2013
Expire Date Thu May 02 06:33:19 PDT 2013  - 1367501655

BUILD SUCCESSFUL
 

 References:

 JWT Specification 
 Bearer Token Specification
 Assertion Flow Specification 


Creating a MSOL Service Principal Name

       After installing the Office 365 Command Let Module, Open the Power Shell Window and Please run the following command to import the Office 365 Command lets.

Import-Module MsOnlineExtended -Force
  • Connect the Office 365 
     Run the Following Command to establish the connectivity from your local server to office 365.
    
Connect-MsolService  
  • Create the Service Principal Name  
 Run the following command to create the service principal name.

New-MsolServicePrincipal -ServicePrincipalNames ServicePrincipalId/Tenant.com -DisplayName "Service Principal Name"

After running the above command it will create the service principal name and generate the symmetric key.  Please store the symmetric key in safe location.

References:
Service Principal Name