> For the complete documentation index, see [llms.txt](https://help.santesuite.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.santesuite.org/developers/service-apis/openid-connect/supported-grant-types.md).

# Supported Grant Types

SanteDB supports four different grant types described in this session. The grant types and flows are not described here. For a good reference on OpenID Connect flows see [RFC67849](https://tools.ietf.org/html/rfc6749#section-1.3).

You can limit the types of grants each device, application, and security role are allowed to authenticate by denying the following policies on those objects:

| Policy                                                               | Grant              | Description                                                                                                               |
| -------------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| OAUTH Login (1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0)                      | Any                | When denied, the specified object cannot authenticate using OAUTH or OpenID Connect.                                      |
| OAUTH password flow (1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0.2)            | Password           | When denied, the specified object is prohibited from using the password grant flow.                                       |
| OAUTH client\_credentials flow (1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0.1) | Client Credentials | When denied, the specified object is prohibited from using the client\_credentials grant flow.                            |
| OAUTH authorization code flow (1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0.3)  | Authorization Code | When denied, the specified object is prohibited from using the authorization\_code grant flow.                            |
| OAUTH password reset flow (1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0.4)      | x\_challenge       | When denied, the specified object is prohibited from using the extended TFA challenge authentication for password resets. |
|                                                                      | x-refresh-cookie   | For the dCDR instances which use cookie based authorization, instructs the oauth provider to use the sent cookie.         |

### Password Grant

The password grant is a grant whereby a trusted user agent (mobile app, website, etc.) collects both the username and password for the user which are then sent to the IdP server.

This grant is useful for:

* Authenticating users from an offline application context (periodic authentication where the UA collects passwords anyways)
* Authenticating users from a first party application or trusted application

![](/files/-MDuUvIbimkupSxUA45v)

The process is as follows:

1. User Agent uses OIDC discovery to determine appropriate scopes, grants, and configuration of the remote target.
2. User agent collects username and password (not specified how)
3. User agent requests an access token from the IdP
4. The IdP responds with an id\_token, auth\_token, refresh\_token for subsequent use.
5. The user agent continues to access the protected resource.

The request for a token using the password is illustrated below:

```http
POST http://mpi-test.local:8080/auth/oauth2_token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: mpi-test.local:8080
Authorization: BASIC XXXYXYYXYXYX
Content-Length: 146

grant_type=password&username=user&password=@Pass123&scope=*&client_id=mymobileapp
```

The `Authorization` header of the OAUTH token is used when the deployment of SanteDB is not using client certificate authentication to validate nodes. It expresses the device credentials (device ID and device secret) and establishes the device principal on the access token.

The `client_id` is mandatory, and must match the registered application credential configured in SanteDB. `client_secret` is optional, if supplied it must carry the registered secret for the secure application.

#### Multifactor Authentication

If the user account or server requires multi-factor authentication, the iCDR will response with a 401 and carry an `error`  of `mfa_required` along with an `error_message` generated by the user's configured MFA type:

```json
{
  "error": "mfa_required",
  "error_description": "Multi-factor Authentication is Required - Open your authenticator app and enter the secret generated"
}
```

The client is expected to collect the MFA code from the user and then pass the MFA code in the subsequent password grant request in the `x_mfa` field.

{% hint style="info" %}
Future versions of SanteDB may use the `client_assertion` field carrying the MFA code in the assertion body.
{% endhint %}

#### Required Assertions

Some deployments of SanteDB require additional information for login beyond the base OpenID Connect username and password. When this condition is detected, the iCDR will respond with a `400 Bad Request` and a body indicating the missing claims

```json
{
    "error":"missing_claim",
    "error_description":"Please select the facility in which you are working for this session",
    "data": {
        "claimType": "urn:oasis:names:tc:xspa:1.0:subject:facility",
        "claimValue":"4413ac96-387f-47e0-bf28-d207761bced6=National Referral Hospital,16966df7-cf9d-470d-988e-c6ccd957a89f=Pear County Community Hospital,fcdcf690-b4d3-4e84-9a2d-e77b9b6f11b8=Bengal County Village Clinic,774dc415-6bfb-4cf5-a2c4-cca6fa22f3ea=Fuji Community Hospital"
    }
}
```

The `data` property will contain the ID of the missing claim, and the permitted values for the missing claim. In the example above, the user has failed to submit the `faciliy` claim, and the server is providing a list of appropriate values for the claim.&#x20;

The requestor is expected to collect the claim value, and then submit the user-selected value in either the `X-SanteDB-ClientClaim` header or the `client_assertion` property.

### Client Credentials Grant

The client credentials grant creates an application principal based on the device/application pair presented on the authentication request.

This grant is useful for:

* A background task from a trusted application on a trusted device (like synchronization)
* HIE traffic between nodes / applications where dual-PKI infrastructure is prohibitively complex.

![](/files/-MDuZhQYAjk-7_ao6804)

The process for this is:

1. User agent runs a discovery request (optional)
2. User agent sends a token request (client\_credentials grant)
3. User agent receives an application authentication token
4. User agent accesses the resource

A client credentials grant is illustrated below:

```http
POST http://mpi-test.local:8080/auth/oauth2_token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: BASIC RGVidWdlZS1FMEQ1NUVBNUQ2Q0Q6MCpTdV8yfk9kSjdAR2NjNw==
Host: mpi-test.local:8080
Content-Length: 112

grant_type=client_credentials&scope=*&client_id=myMobileApp&client_secret=myAppSecret
```

SanteDB's IdP mandates that application principals can only be created if the device is known. The device identity can be established from client-certificates (if configured), or in a simpler deployment, using the device's identifier and secret in the X-Device-Authorization header.

### Authorization Code Grant

The authorization code grant is a traditional OpenID connect grant flow you've probably seen used online. The authorization code grant does not expose the user name or password to the client application. Rather, the user is redirected to the SanteDB IdP server where their credentials are collected by SanteDB and the resulting authorization code is sent back to the UA.

This grant is helpful when:

* Integrating third party applications where you may or may not trust the application&#x20;
* SSO where you wish to use cookies to auto-login users.

![](/files/-MDub-sLug3S0v-UDc_p)

The process for this is:

1. User is directed to the login screen on SanteDB's IdP (established from OIDC discovery)
2. User enters their username and password into the IdP
3. IdP generates an authorization code and redirects the user's browser back to the application requesting the token
4. Application uses the authorization code provided to exchange for auth tokens
5. IdP validates the authorization code and responds with token.
6. Application accesses the protected resource.

In this flow the first step is a redirection to the IdP supplying the minimum parameters:

```
GET http://server:8080/auth/authorize/index.html?redirect_uri=http://myapp.com&client_id=fiddler&scope=openid&response_type=code&response_mode=query&state=1234
```

The parameters for this initial request are:&#x20;

| Parameter      | Description                                                                                                                                                                                                                                                                                      | Values              |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- |
| redirect\_uri  | The URI where the IdP should redirect the user's browser                                                                                                                                                                                                                                         |                     |
| client\_id     | <p>The client identification of the requestor (note: must have grant</p><p>to do authorization code flow)</p>                                                                                                                                                                                    |                     |
| scope          | <p>The scope of the grant . Must contain openid, optionally can <br>contain additional policies being requested)</p>                                                                                                                                                                             | openid              |
| claim          | Claims made about the user separated                                                                                                                                                                                                                                                             |                     |
| state          | <p>A unique state identifier which can be used to maintain <br>state across requests</p>                                                                                                                                                                                                         |                     |
| response\_type | <p>The type of response being asked for.</p><p>code => The redirect is supplied a code which can be exchanged</p><p>token =></p>                                                                                                                                                                 | code or token       |
| response\_mode | <p>The mode of response. </p><p>query => The redirect will be made via a GET operation with the <br>authorization code being the supplied as a query parameter.</p><p>post => The redirect will be made via a POST operation with the authorization code being supplied as a form parameter.</p> | form\_post or query |
| nonce          | A unique NONCE which is passed back to the requestor to ensure tampering has not occurred.                                                                                                                                                                                                       |                     |

The user will be presented with the defined IdP login screen (specified in the applets manifest).

![](/files/-MDufUSpDwv1ylxNMtfA)

If successful, the browser will be redirected back to the caller.&#x20;

When an response\_type = code and response\_mode = query, a simple redirect is performed&#x20;

```http
HTTP/1.1 302 Found
Content-Length: 0
Location: http://myapp.com/auth_back?code=907...8D808&state=1234
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 04 Aug 2020 18:16:10 GMT
```

When response\_type = code and response\_mode = form\_post, a form post is returned

```http
HTTP/1.1 200 OK
Content-Length: 584
Content-Type: text/html
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 04 Aug 2020 18:27:42 GMT

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <body onload="javascript:document.forms[0].submit()">
        <form method="POST" action="http://localhost">
            <input type="hidden" name="code" value="kKrL...YCA" />
            <input type="hidden" name="state" value="1234" />
            <button type="submit">Complete Authentication</button>
        </form>
    </body>
</html>
```

If using response\_type = token and response\_mode = form\_post, a form post with an auth token is directly sent back to the UA for use with the assigned resource. This may be disabled based on your configuration.

```http
HTTP/1.1 200 OK
Content-Length: 538
Content-Type: text/html
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 04 Aug 2020 18:33:15 GMT

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <body onload="javascript:document.forms[0].submit()">
        <form method="POST" action="http://localhost">
            <input type="hidden" name="access_token" value="D8A29CF...17335628" />
            <input type="hidden" name="state" value="1234" />
            <button type="submit">Complete Authentication</button>
        </form>
    </body>
</html>
```

### Challenge Grant

The `x_challenge` grant is a special SanteDB grant explicitly intended for facilitating user password resets using a security challenge question. The iCDR restricts challenge grant sessions to `Change Password` , no other permissions are granted.

The challenge grant accepts a `challenge` and a `response` property in addition to the username. The challenge grant MUST include the device credentials and acts as a `client_credentials` grant. Challenge grants can be disabled via setting the `1.3.6.1.4.1.33349.3.1.5.9.2.1.0.0.4` policy of the client and/or device to DENY.

```http
POST /auth/oauth2_token HTTP/1.1
Accept: application/json
Connection: keep-alive
Content-Length: 157
Content-Type: application/x-www-form-urlencoded

client_id=org.santedb.disconnected_client.www&username=fujiman&
challenge=4248a866-ec00-11f0-81c3-33510c284261&response=sibling&
grant_type=x_challenge&scope=*
```
