government of the people’s republic of...
TRANSCRIPT
Government of the People’s Republic of Bangladesh
Access to Information (a2i)-II Programme
ICT Tower, Agargaon, Dhaka
PROJECT NAME
Single Citizen Service Platform for Government & Business
DOCUMENT NAME
Technical Documentation for Single-Sign-On (SSO) Integration
(Live Server)
PREPARED BY
Dated: 11 July 2019 Version: 2.0
2 | P a g e
Table of Content
1.0. What is Single-Sign-On (SSO)? .................................................................................... 3
2.0. Why SSO is used in EkSheba Government Project? ..................................................... 4
3.0. Benefits of using Single-Sign-On (SSO)? ...................................................................... 4
4.0. How does SSO work? .................................................................................................. 5
5.0. Elements of SSO in EkSheba Government ................................................................... 6
5.1.1. OAuth 2.0 with OpenID Connect .......................................................................... 6
Roles of OAuth: OAuth defines four roles: ........................................................................ 6
Resource Owner: User ...................................................................................................... 6
Resource / Authorization Server: API .................................................................................. 6
Client: Application ............................................................................................................ 6
5.1.2. Single-Sign-On Widget ......................................................................................... 8
5.1.3. Identity Provider / Identity Server: ...................................................................... 9
6.0. Basic Flow of SSO adopted in EkSheba Government ................................................. 10
6.1.1. Use Cases .......................................................................................................... 10
6.1.2. Steps of Single-Sign-On ...................................................................................... 13
7.0. How to get Onboarded to avail the SSO Service of EkSheba Government ................. 15
8.0. Understanding the Libraries ..................................................................................... 18
8.1.1. SSO Library Structure ......................................................................................... 18
8.1.2. Widget Library ................................................................................................... 20
8.1.3. Server side Consideration for Widget ................................................................ 21
9.0. Integration with Common Frameworks .................................................................... 23
9.1.1. Laravel Integration ............................................................................................ 23
9.1.2. CakePHP Integration .......................................................................................... 31
9.1.3. Java Spring Boot Integration .............................................................................. 37
3 | P a g e
1.0. What is Single-Sign-On (SSO)?
Single-Sign-On (SSO) is a mechanism to control access of users to a system, where a user logs
in with a single username and password to gain access to digital system(s). The major benefit
of this mechanism is, the user do not need to remember or use multiple usernames and
passwords.
When multiple digital services that contain similar or correlated features, there comes a
requirement of Single-Sign-On facility, because otherwise for accessing each service there
would require different usernames and passwords (therefore, credential) which will become
unmanageable. Moreover, accessing one service after another to do a task will become much
troublesome. To solve this problem, Single-Sign-On is a wonderful mechanism.
In this mechanism of Single-Sign-On there remains an Identity Provider which contains a
lookup facility that provides mapping between network resources (in our case, different
digital services), and this Identity Provider facilitates same credential, and same access token
to enter multiple services.
If even different digital services are of different type of authentication and login process, the
Single-Sign-On mechanism makes it very simple by facilitating a single way login mechanism.
Figure: Single-Sign-On Architecture
4 | P a g e
2.0. Why SSO is used in EkSheba Government Project?
EkSheba Government is such a platform with which all government digital services (known as,
e-Services) will be connected. As one government e-Service will have relation to another e-
Service, therefore a common access mechanism should be there while a government official
accesses an e-Service to facilitate citizen.
As an example scenario, if an Officer of Passport Office wants to process a passport of any
citizen, he will require to access the e-Service Portal of Passport Office. Here, to verify a
passport applicant’s NID the Officer may require to access the e-Service Portal of Election
Commission as well. In such situation, if the Officer of Passport Office would get two different
access credential for the two e-Service Portals, and if the Officer would require to access them
separately, then his task would become complex and time lengthy. For this reason, the
EkSheba Government Project’s SSO mechanism has made the life of Government Officers
easy by making a single login credential and single authentication mechanism.
3.0. Benefits of using Single-Sign-On (SSO)?
There are so many benefits of SSO. The major benefits of SSO are:
As SSO takes the responsibility of user authentication centrally, the services (that are
going to use SSO) doesn’t require to think about implementing authentication again.
The authentication and login management becomes centralized and independent.
User doesn’t require to remember multiple usernames and passwords for multiple
services.
The time to do activities on multiple services gets reduced as access to the services
become so quicker using same credential.
IT support expense reduces as calls regarding password change and recovery reduces.
As it facilitates one URL, one Profile, one ID, one Password, therefore it removes the
redundancy for the users.
For enterprise ecosystems where multiple digital services are centralized, and users of the
ecosystem needs to access each digital service quickly with a single credential, then SSO has
no alternative.
5 | P a g e
4.0. How does SSO work?
There are different protocols (standard and of transmission) of Single-Sign-On. Among these,
for EkSheba Government, the OpenID Connect (OIDC) is used on the top of OAuth2.0
Authorization Framework.
OpenID Connect (OIDC) is an authentication protocol that uses JSON Web Token (JWT), a type
of token to validate and approve a login attempt.
And, OAuth 2.0 Authorization Framework uses this OIDC protocol, and facilitates both
authentication and authorization facility.
Here, Authentication is the process of verifying the identity of a user by obtaining some sort
of credentials for example his username password combination, and using those credentials
to verify the user’s identity.
While, Authorization is the process of allowing an authenticated user to access his resources
by checking whether the user has access rights to the system. You can control access rights
by granting or denying specific permissions to an authenticated user. So, if the authentication
was successful, the authorization process starts. Authentication process always proceeds to
Authorization process.
When a user is authenticated using SSO to access to any specific digital service, the “Identity
Provider” of SSO issues an Access Token therefore an “Identity” to that the digital service can
approve the user to access it.
Therefore, an Identity Provider offers user authentication as a service. An identity provider is
a trusted provider that lets user use Single-Sign-On (SSO) to access software systems.
While implementing SSO mechanism, Solution Architects use a type of Widget which helps
user to switch among software systems that are connected with the SSO.
Widget, in general terms, is an independent web element which can be placed commonly on
the user interface of any website or software to facilitate a set of features.
All the above explained elements are part of the deployment of SSO mechanism using OAuth
2.0. OAuth is not only a simple way to publish and interact with protected resource data, but
it is also a safer and more secure way for people to give you access to their resource data.
Organizations that have started to use OpenID Connect with OAuth 2.0 includes Amazon,
Google, Facebook, IBM, Microsoft, Salesforce, VMWare etc.
6 | P a g e
5.0. Elements of SSO in EkSheba Government
5.1.1. OAuth 2.0 with OpenID Connect
OAuth 2 is an authorization framework that enables applications to obtain limited access to
user accounts on an HTTP service. It works by delegating user authentication to the service
that hosts the user account, and authorizing third-party applications to access the user
account. OAuth 2 provides authorization flows for web and desktop applications, and mobile
devices.
Roles of OAuth: OAuth defines four roles:
Resource Owner
Client
Resource Server
Authorization Server
We will detail each role in the following subsections.
Resource Owner: User
The resource owner is the user who authorizes an application to access their account. The
application's access to the user's account is limited to the "scope" of the authorization
granted (as an example, read or write access).
Resource / Authorization Server: API
The resource server hosts the protected user accounts, and the authorization server verifies
the identity of the user then issues access tokens to the application.
From an application developer's point of view, a service's API fulfills both the resource and
authorization server roles. We will refer to both of these roles combined, as
the Service or API role.
Client: Application
The client is the application that wants to access the user's account. Before it may do so, it
must be authorized by the user, and the authorization must be validated by the API.
7 | P a g e
Figure: OAuth 2.0
8 | P a g e
5.1.2. Single-Sign-On Widget
In general terms, a Widget is an independent web element which can be placed commonly
on the user interface of any website or software to facilitate a set of features.
SSO Widget is placed in the header of all e-Services (Government Digital Services) that are
connected to the EkSheba Government SSO. Using this widget users will able to switch from
one application to another. For example user will able to switch from Nothi system to GRS
system using this widget. A snapshot of widget of single-sign-On (SSO) is given below:
Figure: Snapshot of the Widget of Single-Sign-On (SSO)
9 | P a g e
5.1.3. Identity Provider / Identity Server:
An identity provider (abbreviated as IDP) is a system entity that creates, maintains, and manages
identity information for principals while providing authentication services to relying software systems
within a distributed network.
Identity providers offer user authentication as a service. Relying party software systems outsource the
user authentication step to a trusted Identity Provider.
In generic terms, an Identity Provider is a trusted provider that lets user to use single sign-on (SSO) to
access other software systems.
Figure: Snapshot of the Widget of Single-Sign-On (SSO)
10 | P a g e
6.0. Basic Flow of SSO adopted in EkSheba Government
6.1.1. Use Cases
In EkSheba Government there are three (3) use cases of Single-Sign-On.
Use Case 1:
1. User will put http://doptor.gov.bd on browser, it will redirect to Identity Provider (the
central authentication system of users).
2. User will put username and password.
3. After successfully authentication, user will be redirected to landing page of Doptor.
4. Here user will see configurable dashboard with all permitted software systems.
5. By clicking on software systems icon, user will able go landing page of corresponding
software system.
Figure: Use Case 1 of SSO
11 | P a g e
Use Case 2:
1. User will put URL of application software (as an example, http://nothi.gov.bd) in browser,
it will redirect to Identity Provider (central authentication system of users).
2. User will put username and password.
3. After successfully authentication, user will redirect to landing page of corresponding
software (as an example, Dashboard of Nothi).
4. Here user will see Widget (an independent web element with a set of features) with all
permitted software systems. By clicking on software systems icon in Widget, user will able
go landing/dashboard page of corresponding software system.
Figure: Use Case 2 of SSO
12 | P a g e
Use Case 2:
1. User will put URL of software (as an example, http://grs.gov.bd) in browser which is the
landing page of the software (here, landing page of GRS is http://grs.gov.bd).
2. After clicking on login link, it will redirect to Identity Provider (central authentication
system of users).
3. User will put username and password.
4. After successfully authentication, user will redirect to landing page of corresponding
software (as an example, Dashboard of GRS).
5. Here user will see Widget with all permitted software systems. By clicking on software
systems icon in Widget, user will able go landing/dashboard page of corresponding
software.
Figure: Use Case 3 of SSO
13 | P a g e
6.1.2. Steps of Single-Sign-On
The steps of SSO are explained as follows:
1. User needs to browse the URL of any software system. As an example for Nothi e-Service:
http://nothi.gov.bd
2. System will redirect the user to the Identity Provider Server (therefore, Identity Server):
http://idp.doptor.gov.bd
3. User will provide username and password (therefore credentials).
4. Identity Server will authenticate the user.
5. Identity Server will send Token (JSON Web Token) to the software system with
authentication information.
6. Software system will redirect user to the landing page (therefore, Dashboard) after
authentication process is done.
The sequential flow of SSO is as follows:
Figure: Sequence Diagram of SSO
14 | P a g e
The application to application login sequential flow of SSO is as follows:
Figure: App to App Login Sequence Diagram
15 | P a g e
7.0. How to get Onboarded to avail the SSO Service of EkSheba
Government
Any organization that is intending to get connected to the EkSheba Government ecosystem
are required to follow the steps below:
Figure: Steps to get onboarded to avail SSO mechanism of EkSheba Government
16 | P a g e
The process is explained here for better understanding:
1. Visit the website: http://doptor.gov.bd/standard/portal/serviceregistration
2. Read the instructions and click on the red colored “Link” text.
3. You will get an organization registration form, fill it up with all necessary information:
17 | P a g e
Here you will be asked for:
System Name: The name of your e-Service System.
System Bangla Name: The name of your e-Service System in Bengali.
System URL: Link of your e-Service.
Default Page URL: Link of the default page (dashboard) of your e-Service.
Logout URL: Link of the page where you want to redirect your user after logout.
Mobile No: Official contact number of the organization of the e-Service.
Email Address: Official email address of the organization of the e-Service.
Notification Mechanism: How do you want the notification, over Email or over
SMS?
4. EkSheba Government website will provide you SSO library. If you didn't receive, then
please request for it from EkSheba Government Admin.
5. Use the provided library to write necessary functions in controller or other places of your
e-Service.
6. Add Widget to your e-Service by adding JavaScript and CSS library.
18 | P a g e
8.0. Understanding the Libraries
8.1.1. SSO Library Structure
The SSO folder contains all the necessary classes required for SSO integration. Please keep
the SSO folder inside App\Model namespace. Following classes are important:
Class No: 1
Class Name: SSOConstants
Class Description: This class contains following important information:
a. APP_ID: Application ID
b. SHARED_SECRET: Application Secret Key
c. LANDING_PAGE_URI: IDP will post back to this URL, so that, after login, application
can load this URI.
Class No: 2
Class Name: AppLoginRequest
Class Description: This class will contain necessary function to build request to IDP
$appLoginRequest = new AppLoginRequest();
$appLoginRequest->setLandingPageUrl($landingPageUrl);
$requestUrl = $appLoginRequest->buildRequest();
Class No: 3
Class Name: AppLoginResponse, AppLoginResponseDTO
Description: This class will contain necessary functions for parsing IDP response:
$appLoginResponse = new AppLoginResponse();
$response = $appLoginResponse->parseResponse($token,$nonce);
// after parsing, we will get response type of class AppLoginResponseDTO
// $response contains all necessary user information.
19 | P a g e
//var_dump($response->getUserName());
//var_dump($response->getDesignation());
//var_dump("please provide dashboard");
//var_dump($response->getUserName());
//var_dump($response->getEmployeeRecordId());
//var_dump($response->getOfficeId());
//var_dump($response->getDesignation());
//var_dump($response->getOfficeUnitId());
//var_dump($response->getInchargeLabel());
//var_dump($response->getOfficeUnitOrganogramId());
//var_dump($response->getOfficeNameEng());
//var_dump($response->getOfficeNameBng());
//var_dump($response->getOfficeMinistryId());
//var_dump($response->getOfficeMinistryNameEng());
//var_dump($response->getOfficeMinistryNameBng());
//var_dump($response->getUnitNamEng());
//var_dump($response->getUnitNameBng());
//var_dump($response->getLandingPageUrl());
20 | P a g e
8.1.2. Widget Library
To switch among applications using the widget is necessary. To use the widget library in an e-
Service the following steps should be followed:
1. In the Head section of your Page, include the following Script Tag:
<script type="text/javascript"
src="http://idp.doptor.gov.bd/sso/lib/script.2.min.js"> </script>
2. Add CSS Library in the Head section of your Page:
<link rel="stylesheet" type="text/css" href="
http://idp.doptor.gov.bd/sso/lib/style.css "/>
3. Add the widget initialization parameters as well in your Page:
(JS) widget.init ({
"widgetColor": "light",
"widgetSize": "20px",
"appPermissionURL": </url/to/apicaller>
});
Point to remember that, a parameter is used here, named appPermissionUrl. Its value will
be a valid URL in your own server. From this path the SSO JavaScript widget will expect a list
of permitted apps for the logged in user. SSO JavaScript widget will collect the info via AJAX
call to your server in the assigned URL.
That’s it for the client side. Further specifications are described below accordingly.
21 | P a g e
8.1.3. Server side Consideration for Widget
Till now the 2 step client side updates are done. Those are quite straight forward. Now the
updated JavaScript library will do the task of rendering the custom widget as per the logged
in user.
But for this, SSO JavaScript library needs to know about the permitted apps. But most
commonly the user session information are not stored in the client side for security concerns.
So we are also not eager to put a security flaw.
To work-around the probable security pitfalls (CORS, JSONP), we rather incline to the server
backend of the SSO Client (as an example: Nothi, GRS, eCourt etc).
The logged in user’s permitted apps list is transported to the SSO JS library from EkSheba
Government by means of an AJAX call via the 3rd party SSO Client (Nothi, GRS, eCourt etc)
itself. That is the URL to be put in the appPermissionUrl parameter of the widget initialization.
This requires to be an AJAX URL to return a list of integers/strings. This URL resides in the SSO
Client app. And the system developers are at their freedom whatever the URL might be. Just
it needs to be same in both cases (widget initialization and server AJAX implementation).
The Three (3) Steps:
1. Store the designation_id or office_unit_organogram_id of the logged in user in the HTTP
Session. This information is passed to the SSO Client while the user Logs In.
a. It will be used as a parameter for collecting the system permission.
b. Store it in the session following a method suitable for your system.
2. Implement a functionality to call the REST API from your server backend to collect the
user app permissions. Remember one thing that, currently this API returns a list of App
IDs, which is kept like this way for further use. However, the API URL is:
http:// doptor.gov.bd:8090 /identity/designation/ { designationId } /apps
Here, remember that:
a. {designationId} is the designation ID. Take it from http session as saved earlier.
b. Remember to add the API security token in the header while calling.
22 | P a g e
c. Return the result without any modification to the AJAX caller from the SSO
JavaScript library (just return the value from the function).
3. Map the function to the appropriate URL as per the widget initialization parameter
(appPermissionUrl).
23 | P a g e
9.0. Integration with Common Frameworks
9.1.1. Laravel Integration
1. Create a new project suppose SSODemo, in Laravel with the following composer
command:
laravel new SSODemo
2. Please keep the SSO folder in app/model.
3. In SSOConstants.php file please change the following App ID and secret will be provided
by admin:
a. APP_ID: Application ID
b. APP_NAME: Application Name
c. SHARED_SECRET: Application Secret Key
d. LANDING_PAGE_URI: IDP will post back to this URI. So that, after login,
application can load this URI.
4. http://domain-url/SSODemo/public/ in browser will provide the following page. This
indicates that, laravel is installed properly.
24 | P a g e
5. Add the following library in composer.json:
"require": {
"firebase/php-jwt": "5.0.0"
},
6. Inside routes\web.php add the following:
Route::get('/’,'SSOLoginController@ssologin');
Route::post('applogin','SSOLoginController@applogin');
Route::get('ssologout','SSOLoginController@ssologout');
7. Inside App\Http\Middleware\VerifyCsrfToken.php add the following code:
protected $except = [
'ssologin', 'applogin’, 'ssologout'
];
25 | P a g e
8. Inside the file App\Http\Controller\SSOLoginController.php add the following code. The
applogin() get function will just redirect to the IDP login page. Now let us examine the
applogin() post function.
If we can reach the green text, then our user is authenticated and please take action (give
dashboard/session etc) accordingly. But if we reach the brown then user failed to
authenticate and redirect to the IDP login page.
NOTE: Example below are for explanation. Please do not copy paste from here. Rather a
controller will be attached with library as an example.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Redirect;
use \Firebase\JWT\JWT;
use App\Model\SSO\AppLoginRequest;
use App\Model\SSO\AppLoginResponse;
use App\Model\SSO\AppLogoutRequest;
class SSOLoginController extends Controller
{
public function ssologin()
{
$appLoginRequest = new AppLoginRequest();
$requestUrl = $appLoginRequest->buildRequest();
$nonce = $appLoginRequest->getReqNonce();
$request->session()->put("nonce", $nonce);
return Redirect::to($requestUrl);
}
public function applogin(Request $request)
{
try {
$token = $request->input('token');
$nonce = $request->session()->get("nonce");
$appLoginResponse = new AppLoginResponse();
$response = $appLoginResponse->parseResponse($token, $nonce);
26 | P a g e
$request->session()->put('username', $response->getUserName());
$request->session()->forget("nonce");
// User is authenticated at this point. Please provide him session.
// Class AppLoginResponse() will contain all the necessary information
// var_dump($response->getUserName());
// var_dump($response->getDesignation());
// var_dump("please provide dashboard");
// var_dump($response->getUserName());
// var_dump($response->getEmployeeRecordId());
// var_dump($response->getOfficeId());
// var_dump($response->getDesignation());
// var_dump($response->getOfficeUnitId());
// var_dump($response->getInchargeLabel());
// var_dump($response->getOfficeUnitOrganogramId());
// var_dump($response->getOfficeNameEng());
// var_dump($response->getOfficeNameBng());
// var_dump($response->getOfficeMinistryId());
// var_dump($response->getOfficeMinistryNameEng());
// var_dump($response->getOfficeMinistryNameBng());
// var_dump($response->getUnitNamEng());
// var_dump($response->getUnitNameBng());
// var_dump($response->getLandingPageUrl());
// User is authenticated give session/dashboard/default page.
// Redirect to $response->getLandingPageUrl();
return view('widget');
}
catch (\Exception $ex) {
// User failed to authenticate.
// Because of invalid shared secret, nonce etc.
// Please show an error page.
// Please do not redirect to login page again.
// Please do not give users sessions.
dd($ex);
}
}
public function ssologout(Request $request)
{
//Please invalidate your sessions
$appLogoutRequest = new AppLogoutRequest();
$requestUrl = $appLogoutRequest->buildRequest();
return Redirect::to($requestUrl);
}
}
27 | P a g e
9. After adding the codes, now if everything is correct hitting the e-Service Domain of
EkSheba Government, as an example: http://grs.gov.bd, it will redirect to the IDP login
page.
For example: hitting http://doptor.gov.bd/ gives the following page. Note the URL here
is: http://idp.doptor.gov.bd:
Figure: Login page of central authentication System (IDP Server)
10. Enter the username and password. IDP will post necessary information with validation in
applogin() function we added before. If everything is correct, user will get their
dashboard.
11. Till now, the first part is done. We have logged in to our site using identity server. Now
our next task will be to log in to other websites from our own. For this EkSheba
Government is providing a nice widget for switching among sites. Our widget will look as
follows:
28 | P a g e
Figure: Dashboard of Doptor
12. Let’s add the widget library now. Just add an HTML ID sso-widget where you want the
widget to be. Our library will inject the html code automatically. For example, suppose
we want the widget in header. Suppose widget.blade.php is responsible for our header.
Then, in resources\views\widget.blade.php (widget.blade.php is just for an example, it
can be any other file) we can add the following code:
<li class="dropdown dropdown-language" style="margin-top:5px;margin-
right:10px;" id="sso-widget"> </li>
13. Next add widget JavaScript and CSS library in the same widget.blade.php file:
Add JavaScript Library:
<script type="text/javascript"
src="http://idp.doptor.gov.bd/sso/lib/script.2.min.js"> </script>
29 | P a g e
Add CSS Library:
<link rel="stylesheet" type="text/css"
href="http://idp.doptor.gov.bd/sso/lib/style.css"/>
Initialize Widget:
widgetColor: Currently supported values: light, dark.
widgetSize: Please set the widget size according to your need.
<script>
widget.init({
"widgetColor": "light",
"widgetSize": "20px",
"appPermissionURL": </url/to/apicaller>
});
</script>
14. Server side code for widget:
$designationId = 137247; // Should be Taken from Session
$token = <api token>;
$format = "http://doptor.gov.bd:8090/identity/designation/%s/apps";
$url = sprintf($format, $designationId);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER, array( 'Authorization: Bearer $token' ),
));
$result = curl_exec($curl);
curl_close($curl);
echo $result;
30 | P a g e
Finally, the widget will come like follows:
Figure: Single-Sign-On (SSO) Widget
Using this widget user will be able to switch among sites.
31 | P a g e
9.1.2. CakePHP Integration
1. Register application from web portal. Please view section How to get Onboarded to avail
the SSO Service of EkSheba Government for details.
2. Keep SSO library in App\Model namespace, for CakePHP version 3.5 in /src/Model folder
or according to your wish.
3. In SSOConstants.php file please change the following. Here, App ID and Secret will be
provided by admin:
a. APP_ID: Application ID
b. APP_NAME: Application Name
c. SHARED_SECRET: Application Secret Key
d. LANDING_PAGE_URI: IDP will post back to this URI. So, after login, application
can load this URI.
4. Add firebase/php-jwt with composer. You can use the composer command:
composer require firebase/php-jwt
If you want to know more about firebase library then please visit the GitHub Page of
Firebase: https://github.com/firebase/php-jwt
5. We have to add three functions for SSO. Let’s add route for them at first.
Router::scope('/', function ($routes) {
$routes->connect('/', ['controller' => 'SSO', 'action' =>
'login']);
$routes->connect('/applogin', ['controller' => 'SSO', 'action' =>
'applogin']);
32 | P a g e
$routes->connect('/logout', ['controller' => 'SSO', 'action' =>
'logout']);
});
6. Now we have to add those functions in any controller. Suppose the controller is
SSOController (Note that, the controller name is used just for example. You can use other
controller name according to your wish).
public function login()
{
if ($this->request->is('get')) {
$landingPageUrl = $request->input("landing_page_uri");
$appLoginRequest = new AppLoginRequest();
$appLoginRequest->setLandingPageUrl($landingPageUrl);
$requestUrl = $appLoginRequest->buildRequest();
$nonce = $appLoginRequest->getReqNonce();
$session = $this->request->session();
$session->write('nonce', $nonce);
return $this->redirect($requestUrl);
}
}
public function applogin()
{
try {
$token = !empty($this->request->data['token']) ? $this->request-
>data['token'] : '';
$session = $this->request->session();
$nonce = $session->read('nonce');
$appLoginResponse = new AppLoginResponse();
$response = $appLoginResponse->parseResponse($token, $nonce);
// User successfully authenticated
// Please provide him session
// $response contains all the necessary user information.
// var_dump($response->getUserName());
// var_dump($response->getDesignation());
// var_dump("please provide dashboard");
// var_dump($response->getUserName());
// var_dump($response->getEmployeeRecordId());
// var_dump($response->getOfficeId());
// var_dump($response->getDesignation());
// var_dump($response->getOfficeUnitId());
33 | P a g e
// var_dump($response->getInchargeLabel());
// var_dump($response->getOfficeUnitOrganogramId());
// var_dump($response->getOfficeNameEng());
// var_dump($response->getOfficeNameBng());
// var_dump($response->getOfficeMinistryId());
// var_dump($response->getOfficeMinistryNameEng());
// var_dump($response->getOfficeMinistryNameBng());
// var_dump($response->getUnitNamEng());
// var_dump($response->getUnitNameBng());
// var_dump($response->getLandingPageUrl());
return $this->redirect($response->getLandingPageUrl());
}
catch (\Exception $ex) {
// var_dump($ex);
// User failed to authenticate. Guessing invalid nonce, shared secret.
// Invalidate session
// Very important
// Please Show a page with error
}
}
public function logout()
{
//Please invalidate your Sessions
$session = $his->request->session();
$session->destroy();
$appLogoutRequest = new AppLogoutRequest();
$requestUrl = $appLogoutRequest->buildRequest();
return $this->redirect($requestUrl);
}
7. Now if everything is correct, hitting http://domain-url/ (as an example, the URL of GRS:
http://grs.gov.bd) will redirect user to IDP login page. For example browsing
http://doptor.gov.bd/ will give the following page:
34 | P a g e
Note that the URL will be here: http://idp.doptor.gov.bd
Figure: Login Page of Central Authentication System (IDP)
8. Enter user name and password. IDP will post necessary information with validation in
applogin() function we added before. If everything is correct, user will get their
dashboard.
9. Now, we have logged in to our site using identity server. Now our next task will be to log
in to other websites from our own. Thus, EkSheba Government is providing a nice widget
for switching among sites. The widget looks as follows:
Figure: Dashboard of Doptor
35 | P a g e
10. Let’s add the widget library now. Just add an id sso-widget where you want the widget to
be. Our library will inject the html code automatically. For example, suppose we want the
widget in header. Suppose top_bar.ctp is responsible for our header. Then, in
src\Template\Element\top_bar.ctp (top_bar.ctp is just for an example, it can be any other
file) we can add the following code :
<li class="dropdown dropdown-language" style="margin-top:5px;margin-
right:10px;" id="sso-widget"> </li>
11. Add widget’s JavaScript and CSS library in widget.blade.php or in other files:
Add JavaScript Library:
<script type="text/javascript"
src="http://idp.doptor.gov.bd/sso/lib/script.2.min.js"> </script>
Add CSS Library:
<link rel="stylesheet" type="text/css"
href="http://idp.doptor.gov.bd/sso/lib/style.css"/>
Initialize Widget:
widgetColor: Currently supported values: light, dark.
widgetSize: Please set the widget size according to your need.
<script>
widget.init({
"widgetColor": "light",
"widgetSize": "20px",
"appPermissionURL": </url/to/apicaller>
});
</script>
36 | P a g e
12. Server side code for widget:
<?php
$designationId = 137247;
// should be taken from session $token = <api token>;
$format = "http://doptor.gov.bd:8090/identity/designation/%s/apps";
$url = sprintf($format, $designationId);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER,
array(
'Authorization: Bearer $token'
)
));
$result = curl_exec($curl);
curl_close($curl);
echo $result;
13. If we have come to this point, then our widget is done. We should be able to switch among
sites with widget.
37 | P a g e
9.1.3. Java Spring Boot Integration
1. Please register application from portal or request an admin to do it.
2. Please keep the provided library in com.revesoft.sso folder/package.
3. Add maven repository.
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
4. Add the following code in controller:
@Controller
public class SSOLoginController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public void showIDPLoginPage(HttpServletRequest request,
HttpServletResponse response) {
try {
String landingPageUrl =
request.getParameter("landing_page_url");
AppLoginRequest appLoginRequest = new AppLoginRequest();
appLoginRequest.setLandingPageUrl(landingPageUrl);
String authnRequest = appLoginRequest.buildAuthnRequest();
request.getSession().setAttribute("nonce",
appLoginRequest.getNonce());
38 | P a g e
response.sendRedirect(authnRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/applogin", method = RequestMethod.POST)
public void jwtSSO(HttpServletRequest request, HttpServletResponse
response, Principal principal) {
try {
String token = request.getParameter("token");
LoginResponse loginResponse = new AppLoginResponse();
loginResponse.setSessionNonce((String)
request.getSession().getAttribute("nonce"));
SSOResponseDTO ssoResponseDTO =
loginResponse.parseResponse(token);
// User successfully authenticated please provide him session
// ssoResponseDTO contains all the necessary user data
response.sendRedirect(ssoResponseDTO.getLandingPageUrl());
} catch (Exception ex) {
ex.printStackTrace();
// User failed to authenticate
// Please do not provide session
// Show an error page
}
@RequestMapping(value = "/ssologout", method = RequestMethod.GET)
public ModelAndView ssologout(HttpServletRequest request) {
// Please invalidate your sessions.
try {
39 | P a g e
request.getSession().invalidate();
AppLogoutRequest appLogoutRequest = new
AppLogoutRequest();
return new ModelAndView("redirect:" +
appLogoutRequest.buildLogoutRequest());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
5. Let’s add the widget library now. Just add an id sso-widget where you want the widget to
be. Our library will inject the html code automatically. For example, suppose if we want
the Widget in header, we can add the following code :
<li class="dropdown dropdown-language" style="margin-top:5px;margin-
right:10px;" id="sso-widget"> </li>
6. Now let’s add the JavaScript and CSS libraries or other files according to need:
Add JavaScript Library:
<script type="text/javascript" src="
http://idp.doptor.gov.bd/sso/lib/script.2.min.js"> </script>
Add CSS Library:
<link rel="stylesheet" type="text/css" href="
http://idp.doptor.gov.bd/sso/lib/script.2.min.js"/>
Initialize Widget:
widgetColor: Currently supported values: light, dark.
40 | P a g e
widgetSize: Please set the widget size according to your need.
<script>
widget.init({
"widgetColor": "light",
"widgetSize": "20px",
"appPermissionURL": </url/to/apicaller>
});
</script>
7. Server side code for Widget:
package com.revesoft.test;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller public class SSOClientController {
private static final String APP_PERMISSION_URL =
"http://doptor.gov.bd:8090/identity/designation/%s/apps";
private final OkHttpClient client = new OkHttpClient();
@ResponseBody
@GetMapping("/ekSheba-govt/sso/user/apps")
public String getPermittedApps() {
session int designationId = 137247;
try {
41 | P a g e
// get the designation id from the
return client.newCall(new
Request.Builder().url(String.format(APP_PERMISSION_URL,
designationId)).build()).execute().body().string();
} catch (IOException ex) {
return null;
}
}
}