> For the complete documentation index, see [llms.txt](https://docs.digit.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.digit.org/health/deploy/configuration/single-sign-on-ui-technical-guide.md).

# Single Sign On - UI Technical guide

### 1. Overview

The DIGIT Core frontend supports a **provider-agnostic OIDC-based SSO login**. Any OIDC-compliant identity provider (Google, Microsoft Azure AD, Keycloak, etc.) can be plugged in through MDMS configuration — no code changes are required to add new providers.

***

### 2. Key Files and Their Roles

| File                                       | Purpose                                                            |
| ------------------------------------------ | ------------------------------------------------------------------ |
| `micro-ui/web/src/globalConfig.js`         | Runtime configuration — holds OAuth Client ID and JWT token        |
| `micro-ui/.../Login/login.js`              | Core login logic — handles OIDC flow, token exchange, and redirect |
| `micro-ui/.../Login/config.js`             | Fallback login form config used when MDMS config is absent         |
| `micro-ui/.../EmployeeSSOLoginOptions.js`  | SSO button component rendered on the login page                    |
| `micro-ui/.../hooks/useLoginConfig.js`     | Hook to fetch `LoginConfig` from MDMS                              |
| `micro-ui/web/packages/css/.../login.scss` | Styling for the SSO button area                                    |

***

### 3. Authentication Flow

<figure><img src="https://2077406040-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FI0KFbSBTySIQ7TCOKnJF%2Fuploads%2F8XzgorLzI6SLLZLYWrRW%2Fimage.png?alt=media&amp;token=71f1630c-b550-4d73-8c11-3d1bd1ac7bd9" alt=""><figcaption></figcaption></figure>

***

### 4. `globalConfig.js` Configuration

The following keys must be present in `globalConfig.js`:

```javascript
var globalConfigs = (function () {

  var microsoftClientId = "your-google-oauth-client-id.apps.googleusercontent.com";
  // For Google Sign-In: paste your Google OAuth Client ID here.
  // Note: This key is named 'microsoft' for legacy reasons — it works for all providers.

  var microsoftTenantId = "your-state-code";
  // State/tenant code used internally, e.g. "mz", "pg", "pb"

  var jwtToken = "your-base64-encoded-jwt-token";
  // Base64 encoded "client-id:client-secret" for DIGIT backend auth.
  // Fallback default: "ZWdvdi11c2VyLWNsaWVudDo=" (egov-user-client:)

  var getConfig = function (key) {
    if (key === "MICROSOFT_CLIENT_ID") return microsoftClientId;
    else if (key === "MICROSOFT_TENANT_ID") return microsoftTenantId;
    else if (key === "JWT_TOKEN") return jwtToken;
  };

  return { getConfig };
}());
```

> **Note:** `MICROSOFT_CLIENT_ID` and `MICROSOFT_TENANT_ID` are legacy key names. The actual provider type is controlled by MDMS, not `globalConfig`. For Google, set `MICROSOFT_CLIENT_ID` to your Google OAuth Client ID.

***

### 5. MDMS Configuration

SSO providers are configured entirely through MDMS. The login page fetches them using `Digit.Hooks.useSSOConfig(stateCode)`.

#### Module and Master

| Setting | Value               |
| ------- | ------------------- |
| Module  | `SSO`               |
| Master  | `IdentityProviders` |

#### Data Structure

```json
{
  "module": "SSO",
  "masterName": "IdentityProviders",
  "masterData": [
    {
      "id": "google-sso",
      "provider": "GOOGLE",
      "ui": {
        "provider": "GOOGLE",
        "name": "Google",
        "logo": "https://your-assets-bucket/google-logo.svg",
        "authStrategy": "OIDC_POPUP",
        "authorizeUrl": "https://accounts.google.com/o/oauth2/auth",
        "clientId": "your-google-client-id.apps.googleusercontent.com",
        "scopes": ["openid", "profile", "email"],
        "responseType": "id_token",
        "responseMode": "fragment",
        "nonceRequired": true,
        "redirectPath": "employee/user/login",
        "prompt": "select_account",
        "logoutUrl": "https://accounts.google.com/logout",
        "logoutRedirectParam": "continue"
      }
    }
  ]
}
```

#### Field Reference

| Field                    | Type      | Required | Description                                                                        |
| ------------------------ | --------- | -------- | ---------------------------------------------------------------------------------- |
| `id`                     | string    | Yes      | Unique identifier for this provider                                                |
| `provider`               | string    | Yes      | Top-level provider type (`GOOGLE`, `MICROSOFT`, etc.)                              |
| `ui.provider`            | string    | Yes      | Used to apply CSS class and routing logic                                          |
| `ui.name`                | string    | Yes      | Display name — used to generate the localization key `SSO_PROVIDER_<name>`         |
| `ui.logo`                | string    | Yes      | URL to the provider logo shown in the button                                       |
| `ui.authStrategy`        | string    | Yes      | Use `OIDC_POPUP` for redirect-based OIDC flow                                      |
| `ui.authorizeUrl`        | string    | Yes      | OAuth authorization endpoint                                                       |
| `ui.clientId`            | string    | Yes      | OAuth 2.0 Client ID from the identity provider                                     |
| `ui.scopes`              | string\[] | No       | OAuth scopes. Default: `["openid", "profile", "email"]`                            |
| `ui.responseType`        | string    | No       | `id_token` (implicit) or `code` (PKCE). Default: `id_token`                        |
| `ui.responseMode`        | string    | No       | `fragment` (hash) or `form_post`. Default: `fragment`                              |
| `ui.nonceRequired`       | boolean   | No       | Whether to include a nonce. Default: `true`                                        |
| `ui.redirectPath`        | string    | No       | Path after context root for redirect URI. Default: `employee/user/login`           |
| `ui.prompt`              | string    | No       | OAuth prompt value: `select_account`, `consent`, `login`, or `none`                |
| `ui.logoutUrl`           | string    | No       | Provider logout endpoint used during DIGIT logout                                  |
| `ui.logoutRedirectParam` | string    | No       | Query param name for redirect URI in logout URL                                    |
| `ui.resource`            | string    | No       | Microsoft only: Azure resource ID (defaults to `clientId` if omitted)              |
| `ui.tenantId`            | string    | No       | Microsoft only: Azure AD tenant ID                                                 |
| `ui.authority`           | string    | No       | Microsoft only: Authority URL, e.g. `https://login.microsoftonline.com/<tenantId>` |

#### MDMS Response Path

The login component accepts any of these selector paths from the MDMS response:

```
data?.MdmsRes?.["SSO"]?.IdentityProviders
data?.["SSO"]?.IdentityProviders
data?.["IdentityProviders"]
```

***

### 6. Login Form Config

The `EmployeeSSOLoginOptions` component is included in the login form as a field of type `component`.

#### Loading Priority

1. `useLoginConfig` fetches `LoginConfig` from MDMS using the module name from `Digit.Utils.getConfigModuleName()` (the `UICONFIG_MODULENAME` value in `globalConfig`, e.g. `commonHCMUiConfig`).
2. If MDMS returns a config → it overrides the hardcoded config.
3. If MDMS returns nothing → the hardcoded `config.js` is used as fallback.

#### Adding the SSO Component — Code Fallback (`config.js`)

```javascript
{
  key: "employeeSsoLoginOptions",
  type: "component",
  disable: false,
  component: "EmployeeSSOLoginOptions",
  populators: { name: "employeeSsoLoginOptions" },
  isMandatory: false,
  withoutLabel: true,
  renderAfterSubmit: true   // renders below the submit button
}
```

#### Adding the SSO Component — via MDMS `LoginConfig`

Include the same field object in the `inputs` array of your MDMS `LoginConfig` master:

```json
{
  "module": "commonHCMUiConfig",
  "masterName": "LoginConfig",
  "masterData": [
    {
      "texts": {
        "header": "CORE_COMMON_LOGIN",
        "submitButtonLabel": "CORE_COMMON_LOGIN",
        "secondaryButtonLabel": "CORE_COMMON_FORGOT_PASSWORD"
      },
      "inputs": [
        { "label": "CORE_LOGIN_USERNAME", "type": "text", "key": "username", "isMandatory": true, "populators": { "name": "username" } },
        { "label": "CORE_LOGIN_PASSWORD", "type": "password", "key": "password", "isMandatory": true, "populators": { "name": "password" } },
        {
          "key": "employeeSsoLoginOptions",
          "type": "component",
          "component": "EmployeeSSOLoginOptions",
          "populators": { "name": "employeeSsoLoginOptions" },
          "isMandatory": false,
          "withoutLabel": true,
          "renderAfterSubmit": true
        }
      ]
    }
  ]
}
```

***

### 7. Localization Keys

Add these keys to your localization master (e.g. `en_IN`):

| Key                           | Default Value          | Where Used                                       |
| ----------------------------- | ---------------------- | ------------------------------------------------ |
| `CORE_COMMON_OR`              | OR                     | Divider text when there is one SSO provider      |
| `CORE_COMMON_OR_SIGN_IN_WITH` | OR SIGN IN WITH        | Divider text when there are multiple providers   |
| `SSO_PROVIDER_Google`         | Sign in with Google    | Button label — pattern: `SSO_PROVIDER_<ui.name>` |
| `SSO_PROVIDER_Microsoft`      | Sign in with Microsoft | Button label for Microsoft                       |

> The button label key is dynamically generated as `SSO_PROVIDER_<ui.name>`, where `ui.name` is the value set in MDMS.

***

### 8. Backend Token Exchange

The frontend exchanges the OIDC `id_token` for a DIGIT session token via:

```
POST /user/oauth/token
Authorization: Basic <JWT_TOKEN from globalConfig>
Content-Type: application/x-www-form-urlencoded

grant_type=jwt_exchange
scope=read
userType=EMPLOYEE
assertion=<id_token from provider>
access_token=<access_token if available>
tenantId=<state-level-tenant-id>
```

**Expected response:**

```json
{
  "UserRequest": {
    "tenantId": "mz",
    "roles": [{ "code": "EMPLOYEE", "tenantId": "mz" }],
    "name": "John Doe",
    "emailId": "john@example.com"
  },
  "access_token": "...",
  "token_type": "bearer",
  "refresh_token": "..."
}
```

#### Google Cloud Console Setup

1. Go to **Google Cloud Console → APIs & Services → Credentials**.
2. Create an **OAuth 2.0 Client ID** of type **Web Application**.
3. Under **Authorized redirect URIs**, add:

   ```
   https://<your-domain>/<contextPath>/employee/user/login
   ```
4. Copy the generated **Client ID** — this is your `ui.clientId` in MDMS and `microsoftClientId` in `globalConfig`.

***

### 9. Logout Handling

When a user logs in via SSO, the following values are stored in `localStorage` to support provider-side logout:

| Key                         | Value                                | Purpose                                   |
| --------------------------- | ------------------------------------ | ----------------------------------------- |
| `sso-provider`              | `GOOGLE`                             | Identifies the SSO provider used          |
| `sso-logout-url`            | `https://accounts.google.com/logout` | Provider logout endpoint                  |
| `sso-logout-redirect-param` | `continue`                           | Query param name for post-logout redirect |
| `sso-tenant-id`             | Provider tenant ID                   | For Microsoft ADFS logout                 |
| `sso-authority`             | Authority URL                        | For Microsoft ADFS logout                 |

These are set in `onOIDCLogin()` inside `login.js` and should be consumed by the logout handler to redirect to the provider's logout endpoint after clearing the DIGIT session.

***

### 10. CSS Classes

SSO button styles are defined in `micro-ui/web/packages/css/src/pages/employee/login.scss`.

| Class                         | Applied To                                         |
| ----------------------------- | -------------------------------------------------- |
| `.employee-login-sso`         | Wrapper container for the entire SSO section       |
| `.employee-login-sso-divider` | "OR" / "OR SIGN IN WITH" divider line              |
| `.employee-login-sso-icons`   | Grid container when multiple providers are present |
| `.employee-login-sso-icon`    | Individual icon-only button (multiple providers)   |
| `.employee-login-sso-logo`    | Logo `<img>` inside a button                       |
| `.employee-login-sso-button`  | Full-width button (single provider only)           |
| `.<provider>-login-icon`      | Per-provider icon class, e.g. `google-login-icon`  |
| `.<provider>-login-btn`       | Per-provider button class, e.g. `google-login-btn` |

> When `ssoMDMSData` contains **more than one** provider, the component renders icon-only buttons in a grid. For a single full-width labelled button, keep only one entry in `IdentityProviders`.

***

### 11. Component Registration

`EmployeeSSOLoginOptions` is registered via `initCoreComponents()` in `Module.js`:

```javascript
export const initCoreComponents = () => {
  // Fallback for digit-ui-libraries < 1.8.9 that don't include useSSOConfig
  if (!Digit.Hooks.useSSOConfig) {
    Digit.Hooks.useSSOConfig = () => ({ data: [], isLoading: false });
  }

  // Registers the component so FormComposerV2 can render it by name
  Digit.ComponentRegistryService.setComponent("EmployeeSSOLoginOptions", EmployeeSSOLoginOptions);
};
```

> `initCoreComponents()` is called automatically when the core module is bootstrapped.

***

### 12. Troubleshooting

#### SSO button does not appear

* Verify that the `SSO.IdentityProviders` MDMS master exists and is published for your state tenant.
* Check the browser network tab for the MDMS fetch and confirm it returns non-empty data.
* Confirm `initCoreComponents()` was called and `EmployeeSSOLoginOptions` is registered.
* Ensure the `EmployeeSSOLoginOptions` field is present in the `inputs` array of your login config (MDMS or fallback `config.js`).

#### Redirect URI mismatch error from Google

The redirect URI constructed by the frontend is:

```
<window.location.origin>/<contextPath>/<redirectPath>
```

Example: `https://hcm.digit.org/workbench-ui/employee/user/login`

This must **exactly match** what is registered in **Google Cloud Console → OAuth Client → Authorized redirect URIs**. Check `CONTEXT_PATH` in `globalConfig` and `redirectPath` in the MDMS UI config.

#### Token exchange fails (DIGIT Login Failed)

* Verify `JWT_TOKEN` in `globalConfig` is a valid Base64-encoded `<client-id>:<client-secret>` value accepted by your DIGIT backend.
* Confirm the backend `user-service` supports `grant_type=jwt_exchange`.
* Confirm the `tenantId` sent matches an existing tenant in DIGIT.
* The provider must be configured in the DIGIT `user-service` as a trusted OAuth issuer.

#### Login loop / stuck on SSO callback

* If the `id_token` appears in the URL but login fails, `sessionStorage.sso.force.prompt.login` is set to `true` — the next SSO click will force re-authentication.
* The URL is cleared via `window.history.replaceState` after a failed exchange to prevent retry loops.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.digit.org/health/deploy/configuration/single-sign-on-ui-technical-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
