Note: Make sure that you have completed Tutorial 1 and familiarised yourself with the Person JSON schema, and that you have understood the OAuth Process first.
For this tutorial, you will need to call the APIs from your server-based (or running from localhost) application.
Myinfo uses for our Authentication and Authorisation flow.
Please refer to our for this tutorial.
1. Download our Sample Client Application
For the purposes of the tutorial, please download our sample client application from
1.1 Install Node.js and NPM
In order for the demo application to run, you will need to Install Node.js and NPM. Follow the instructions given by the links below depending on your OS.
1.2 Run NPM install
Run the following command in the folder you unzipped the application:
npm install
1.3 Start the Application
For Linux/MacOS
Execute the following command to start the application:
./start.sh
For Windows
Execute the following command to start the application:
.\start.bat
Access the Application on Your Browser
You should be able to access the sample application via the following URL:
http://localhost:3001
2. Trigger MockPass Login and Consent (authorise API)
The authorise endpoint triggers the MockPass login and shows the consent page after successful login.
Click on the "Retrieve Myinfo" button on the sample application.
This calls the URL below (with some additional parameters):
http://sandbox.api.myinfo.gov.sg/com/v3/authorise
This calls the URL below (with some additional parameters):
PARAMETER
DESCRIPTION
client_id
unique ID for your application. For our sample application, this is STG2-MYINFO-SELF-TEST
attributes
comma separated list of attributes requested. Possible attributes are listed in the Person object definition in the API specifications.
purpose
state the purpose of requesting the data. This will be shown to the Person when requesting for his consent
state
identifier to reconcile query and response. This will be sent back to you via the callback URL. Use a unique system generated number for each and every call.
redirect_uri
your callback URL for Myinfo to return with the authorisation code. For our sample application this is http://localhost:3001/callback
Look at the file views/html/index.html in the sample application and look for the following lines of code:
The index.html file is the frontend (client side) code.
You may also use test personas found in the Personas Page when testing Tutorial 2.
2.2 Consent Page
Once you have successfully logged into MockPass, a consent page similar to the one below will be shown:
2.3 Get the Authorisation Code
If you have followed the steps above correctly, the Consent Platform should return you an authorisation code by invoking your callback URL. You should now see something like this in your browser URL dialog:
Notice the parameter code is the authorisation code that your application will need to invoke the next API (token). In the example above, the authorisation code is e2369168-52da-421a-b70f-03f64e779c4b. We will use this authorisation code in the next token API call.
The token and person API calls will follow automatically once you have finished the consent page.
We will look at the code for these 2 APIs in the following sections.
3. Call the Token API (with the authorisation code)
Now that you have the authorisation code, you can invoke the token API to get the access token.
Note: This API must be called from a server-side component. It cannot be called from the browser or mobile native client application due to security reasons (there is no secure place to store your private key).
Look at the code in the file routes/index.js in our sample client application and search for the following:
index.js is the backend (server side) code.
// function to prepare request for TOKEN API
function createTokenRequest(code) {
var cacheCtl = "no-cache";
var contentType = "application/x-www-form-urlencoded";
var method = "POST";
var request = null;
// preparing the request with header and parameters
// assemble params for Token API
var strParams = "grant_type=authorization_code" +
"&code=" + code +
"&redirect_uri=" + _redirectUrl +
"&client_id=" + _clientId +
"&client_secret=" + _clientSecret;
var params = querystring.parse(strParams);
// assemble headers for Token API
var strHeaders = "Content-Type=" + contentType + "&Cache-Control=" + cacheCtl;
var headers = querystring.parse(strHeaders);
// Sign request and add Authorization Headers
var authHeaders = generateAuthorizationHeader(
_tokenApiUrl,
params,
method,
contentType,
_authLevel,
_clientId,
_privateKeyContent,
_clientSecret
);
if (!_.isEmpty(authHeaders)) {
_.set(headers, "Authorization", authHeaders);
}
var request = restClient.post(_tokenApiUrl);
// Set headers
if (!_.isUndefined(headers) && !_.isEmpty(headers))
request.set(headers);
// Set Params
if (!_.isUndefined(params) && !_.isEmpty(params))
request.send(params);
return request;
}
The code is creating the request to call the following API:
https://sandbox.api.myinfo.gov.sg/com/v3/token
Note: This API is using HTTPS POST.
The parameters in the POST body are as follows:
PARAMETER
DESCRIPTION
grant_type
grant type for getting token (default "authorization_code")
code
the authcode given by the authorise API.
redirect_uri
your callback URL for Myinfo to validate. For our sample application this is http://localhost:3001/callback
client_id
unique ID for your application. For our sample application, this is STG2-MYINFO-SELF-TEST
client_secret
secret key given to your application during onboarding. For our sample application, this is 44d953c796cccebcec9bdc826852857ab412fbe2
The sample application will then send the constructed request to the API Gateway, and you should see the following response from the onscreen logs:
Notice the response contains an "access_token", which is in the JWT_ _ (JSON Web Token) format.
3.1 What is the JSON Web Token structure?
JSON Web Tokens consist of three parts separated by dots (.), which are:
Header
Payload
Signature
Therefore, a JWT typically looks like the following: xxxxx.yyyyy.zzzzz
The header and the payload are Base64Url encoded. The signature is created using these two, a secret and the hashing algorithm being used (as specified in the header: HMAC, SHA256 or RSA).
3.2 How can I parse the JWT?
In order to parse the JWT you can use one of the libraries listed in the Libraries for Token Signing/Verification section of JWT.io._ _
For example, in our sample application, which is implemented with Node.js, we use the node-jsonwebtoken library, and we call the jwt.verify() method. If the parsing fails then the library will return a JsonWebTokenError error with the message jwt malformed.
Note: Many web frameworks (such as ASP.NET Core for example) have JWT middleware that handle the token validation. Most of the times this will be a better route to take, rather that resorting to use a third-party library, as the middleware typically integrates well with the framework's overall authentication mechanisms.
Look at the code in the file lib/security/security.js and search for the following code snippet:
// Verify & Decode JWS or JWT
security.verifyJWS = function verifyJWS(jws, publicCert) {
// verify token
// ignore notbefore check because it gives errors sometimes if the call is too fast.
var decoded = jwt.verify(jws, publicCert, { algorithms: ['RS256'], ignoreNotBefore: true });
return decoded;
}
This calls the library to parse the JWT and return the decoded JSON object, which is the access token.
You should see the decoded access token in the onscreen logs that looks like this:
This access token is a representation of the permissions that was given by the user when he/she clicked on "I Agree" on the consent page.
Note:It is very important for your application to validate the signature of the JWT to ensure the response has not been changed in transit.
Notice the sub attribute in the JSON token. That is the identifier of the person who logged in via MockPass. We will use this identifier for the Person API call next.
4. Call the Person API (with the access token)
Now that you have the access token, you can invoke the person API to get the Person data.
Note:This API must be called from a server-side component. It cannot be called from the browser or mobile native client application due to security reasons (there is no secure place to store your private key).
This API call is essentially the same as the one you tried in Tutorial 1, except that here you will need to provide a valid access token or your API call will be rejected.
Look at the code in the file routes/index.js in our sample client application and search for the following:
index.js is the backend (server side) code.
// function to prepare request for PERSON API
function createPersonRequest(sub, validToken) {
var url = _personApiUrl + "/" + sub + "/";
var cacheCtl = "no-cache";
var method = "GET";
var request = null;
// assemble params for Person API
var strParams = "client_id=" + _clientId +
"&attributes=" + _attributes;
var params = querystring.parse(strParams);
// assemble headers for Person API
var strHeaders = "Cache-Control=" + cacheCtl;
var headers = querystring.parse(strHeaders);
var authHeaders;
// Sign request and add Authorization Headers
authHeaders = generateAuthorizationHeader(
url,
params,
method,
"", // no content type needed for GET
_authLevel,
_clientId,
_privateKeyContent,
_clientSecret
);
if (!_.isEmpty(authHeaders)) {
_.set(headers, "Authorization", authHeaders + ",Bearer " + validToken);
}
else {
// NOTE: include access token in Authorization header as "Bearer " (with space behind)
_.set(headers, "Authorization", "Bearer " + validToken);
}
// invoke token API
var request = restClient.get(url);
// Set headers
if (!_.isUndefined(headers) && !_.isEmpty(headers))
request.set(headers);
// Set Params
if (!_.isUndefined(params) && !_.isEmpty(params))
request.query(params);
return request;
}
The code is creating the request to call the following API:
If you have followed the steps above correctly, you should have gotten the Person JSON object. Now you can use this JSON object to prefill the form values in your application.
Look at the code in our sample client application and you will see it is using the response JSON to prefill the values on the application form. Once this is done, the user just needs to submit the form and your application can save the values into your database for subsequent processing.
Summary
You've successfully used the OAuth2 process to get the Person data from Myinfo sandbox environment.