Integrating Using the SDK
There are two main ways of integrating your app with sgID:
Using the Javascript/Typescript SDK
Custom integration by writing your own code for each of the authorization code flow steps
Unfortunately, we only have support for a Javascript SDK, so if your app is written in a different programming language, jump ahead to the next page for the guide on custom integration.
Installing the SDK
npm i @opengovsg/sgid-client
Initializing the SDK
import { SgidClient } from '@opengovsg/sgid-client'
// Replace the values below with your own client credentials
const client = new SgidClient({
clientId: 'CLIENT-ID',
clientSecret: 'cLiEnTsEcReT',
privateKey: '-----BEGIN PRIVATE KEY-----MII ... XXX-----END PRIVATE KEY-----',
redirectUri: 'http://localhost:3000/callback',
})
Creating an authorization URL
To allow your user to login into your app with sgID, you need to create an sgID authorization URL to redirect your user to so that they can authenticate with Singpass.
client.authorizationUrl(state, scope, [nonce], [redirectUri])
// Note: replace the function arguments with your own client data
const { url } = client.authorizationUrl(
'state',
['openid', 'myinfo.nric_number'], // or space-concatenated string
null, // defaults to randomly generated nonce if unspecified
'http://localhost:3000/callback', // overrides redirect uri
)
The full authorization URL should look something like this:
https://api.id.gov.sg/v1/oauth/authorize?
response_type=code
&client_id=abc
&scope=openid%20myinfo.name%20myinfo.passport_expiry_date%20myinfo.nric_number
&redirect_uri=http://localhost:3000/callback
&nonce=BQO8SV3ALIYA808IZ8O7PKWRI8A8X6MI
&state=tk39drykro3
Exchange auth code for access token
After the user authenticates with Singpass, sgID will redirect the user back to the callback URL you provided, together with the authorization code and a state value. Reusing the callback URL defined in the example above:
http://localhost:3000/callback?
code=someauthcode
&state=somestate
Using this authorization code, we can use the SDK to exchange it for an access token, which will be used to retrieve user information.
async client.callback(code, [nonce], [redirectUri])
const { sub, accessToken } = await client.callback(
'code', // auth code reuturned from redirect_url
null,
'http://localhost:3000/callback', // optional, unless overridden
)
Here, the sub
refers to the end user's unique identifier for your client. Note that as part of sgID's privacy-preserving measures, each end user's unique identifier is different for each sgID client.
Request for user info
Once you have the access token, you can use it to request information about the user corresponding to the scopes that you requested.
async client.userinfo(accessToken)
const { sub, data } = await client.userinfo('access_token')
// data: { myinfo.nric_number: "S1231231A", myinfo.name: "JAMUS TAN" }
Last updated