OAuth 2.0 Authentication
Cirrus Shield now provides a built-in OAuth 2.0 Authorization Server. External applications that need to access the Cirrus Shield REST API should authenticate using OAuth 2.0 instead of the legacy username/password token flow.
There are two authentication flows, depending on the type of application:
| Flow | Client Type | Use Case | Has Refresh Token |
|---|---|---|---|
| Client Credentials | Confidential | Back-end services, middleware, ERP integrations, BI tools — no user involved | No |
| Authorization Code + PKCE | Public | Portals, SPAs, mobile apps — a real user logs in | Yes (7 days) |
ℹ️ Before implementing either flow, your application must be registered as a Connected Application in Cirrus Shield. Ask your CS administrator to create the Connected App and provide you with the ClientId and (if Confidential) the ClientSecret.
Base URL
All OAuth endpoints are relative to the Cirrus Shield base URL of your organisation. The base URL follows this pattern:
https://www.cirrus-shield.net
Flow 1 — Client Credentials (Confidential Apps)
Use this flow when your application runs server-side and authenticates in its own name, with no end-user involved. Examples: a background worker syncing invoices, a BI tool pulling CRM data, a middleware posting documents.
How It Works
Your application presents its ClientId and ClientSecret to obtain a short-lived JWT access token. This token is then attached to every API call. When it expires, your application requests a new one using the same credentials.
Step 1 — Request an Access Token
Send a POST request to the token endpoint with your credentials in the Authorization header (HTTP Basic Auth) and the grant type in the body.
Endpoint: POST {baseUrl}/oauth/token
Request (.NET / HttpClient):
var credentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/oauth/token");
request.Headers.Authorization =
new AuthenticationHeaderValue("Basic", credentials);
request.Content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
// optional: new KeyValuePair<string, string>("scope", "api:read api:write"),
});
var response = await httpClient.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
Request (JavaScript / fetch):
const credentials = btoa(`${clientId}:${clientSecret}`);
const response = await fetch(`${baseUrl}/oauth/token`, {
method: "POST",
headers: {
"Authorization": `Basic ${credentials}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
// scope: "api:read api:write", // optional
}),
});
const data = await response.json();
Successful response (200 OK):
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "api:read api:write"
}
ℹ️ No refresh_token is issued for Client Credentials. When the token expires, request a new one using the same ClientId and ClientSecret.
Step 2 — Use the Token
Attach the access token to every API call using the Authorization header. Do not pass it as a query parameter.
.NET:
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
JavaScript:
headers: { "Authorization": `Bearer ${accessToken}` }
Step 3 — Token Lifecycle and Caching
The access token is valid for the duration specified in expires_in (default: 3600 seconds / 1 hour). You should cache the token and reuse it across requests rather than requesting a new one for every API call.
Recommended caching strategy:
- Store the token and its expiry time (current time + expires_in − 60 seconds buffer).
- Before each API call, check if the cached token is still valid.
- If expired, request a new token before proceeding.
- If an API call returns 401 Unauthorized, invalidate the cached token and request a new one, then retry the call once.
Token cache example (.NET):
private string _cachedToken;
private DateTime _tokenExpiresAt = DateTime.MinValue;
public async Task<string> GetTokenAsync()
{
if (_cachedToken != null && DateTime.UtcNow < _tokenExpiresAt)
return _cachedToken;
var token = await RequestNewTokenAsync();
_cachedToken = token.AccessToken;
_tokenExpiresAt = DateTime.UtcNow.AddSeconds(token.ExpiresIn - 60);
return _cachedToken;
}
Error Responses
| HTTP Status | error field | Cause |
|---|---|---|
| 401 Unauthorized | invalid_client | ClientId or ClientSecret is incorrect, or client is disabled |
| 400 Bad Request | invalid_scope | Requested scope is not allowed for this client |
| 403 Forbidden | ip_not_allowed | Request IP is not in the allowed IP list |
| 403 Forbidden | unauthorized_client | client_credentials flow is not allowed for this client |
| 429 Too Many Requests | (header: Retry-After) | Rate limit exceeded — wait the number of seconds in Retry-After |
Error response body:
{
"error": "invalid_client",
"error_description": "Client credentials are invalid or client is disabled."
}
Flow 2 — Authorization Code + PKCE (Public Apps)
Use this flow when a real end-user must authenticate with their own Cirrus Shield account. Examples: a customer portal, a SPA, a mobile app. The user logs in on a Cirrus Shield page and grants your application permission to access their data.
⚠️ PKCE (Proof Key for Code Exchange) is mandatory for all public clients. Only the S256 method is accepted — plain is rejected. Never skip PKCE even if your framework makes it optional.
How It Works
The flow has 4 phases: PKCE generation → user login and consent → authorization code exchange → token use and refresh.
Phase 1 — Generate PKCE Pair
Generate a code_verifier (a random string) and derive a code_challenge from it using SHA-256. The code_challenge is sent to CS; the code_verifier is kept secret and used later to prove your app initiated the flow.
.NET:
// Generate code_verifier
var bytes = new byte[32];
RandomNumberGenerator.Fill(bytes);
var codeVerifier = Base64UrlEncode(bytes); // store in session
// Derive code_challenge
var hash = SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier));
var codeChallenge = Base64UrlEncode(hash); // send to CS
static string Base64UrlEncode(byte[] b) =>
Convert.ToBase64String(b).TrimEnd('=').Replace('+','-').Replace('/','_');
JavaScript:
async function generatePKCE() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const verifier = base64UrlEncode(array); // store in sessionStorage
const hash = await crypto.subtle.digest(
"SHA-256", new TextEncoder().encode(verifier));
const challenge = base64UrlEncode(new Uint8Array(hash));
return { verifier, challenge };
}
function base64UrlEncode(bytes) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
ℹ️ Store the code_verifier in server-side session (.NET) or sessionStorage (JavaScript). You will need it in Phase 3. Never send it over the network before Phase 3.
Phase 2 — Redirect the User to CS Login
Build the authorization URL and redirect the user’s browser to it. Generate a random state value for CSRF protection and store it in session alongside the code_verifier.
Authorization URL parameters:
| Parameter | Required | Value |
|---|---|---|
| response_type | Yes | code |
| client_id | Yes | Your ClientId |
| redirect_uri | Yes | Must exactly match a registered redirect URI |
| scope | Yes | Space-separated scopes, e.g. api:read offline_access |
| state | Yes | Random opaque string — verify it in the callback |
| code_challenge | Yes | SHA-256 base64url of code_verifier |
| code_challenge_method | Yes | S256 (only accepted value) |
.NET:
var state = Guid.NewGuid().ToString("N");
HttpContext.Session.SetString("oauth_state", state);
HttpContext.Session.SetString("pkce_verifier", codeVerifier);
var url = $"{baseUrl}/oauth/authorize" +
$"?response_type=code" +
$"&client_id={Uri.EscapeDataString(clientId)}" +
$"&redirect_uri={Uri.EscapeDataString(redirectUri)}" +
$"&scope={Uri.EscapeDataString("api:read offline_access")}" +
$"&state={Uri.EscapeDataString(state)}" +
$"&code_challenge={Uri.EscapeDataString(codeChallenge)}" +
$"&code_challenge_method=S256";
return Redirect(url);
JavaScript (SPA):
const state = crypto.randomUUID().replace(/-/g, "");
sessionStorage.setItem("oauth_state", state);
sessionStorage.setItem("pkce_verifier", verifier);
const params = new URLSearchParams({
response_type: "code",
client_id: clientId,
redirect_uri: redirectUri,
scope: "api:read offline_access",
state,
code_challenge: challenge,
code_challenge_method: "S256",
});
window.location.href = `${baseUrl}/oauth/authorize?${params}`;
The user will see the Cirrus Shield login page, then a consent screen listing the permissions your application is requesting. After approving, CS redirects to your redirect_uri with a code and the echoed state:
https://yourapp.com/callback?code=ABC123&state=<echo>
⚠️ The authorization code is valid for 60 seconds and can only be used once. Exchange it immediately in Phase 3.
Phase 3 — Exchange the Code for Tokens
In your callback handler: first verify the state parameter, then exchange the code for tokens by sending the code_verifier you stored in Phase 2.
.NET callback handler:
public async Task<IActionResult> Callback(string code, string state, string error)
{
if (!string.IsNullOrEmpty(error))
return RedirectToAction("Error");
// Verify state — CSRF protection
var expectedState = HttpContext.Session.GetString("oauth_state");
if (state != expectedState) return BadRequest("State mismatch.");
var codeVerifier = HttpContext.Session.GetString("pkce_verifier");
HttpContext.Session.Remove("pkce_verifier");
HttpContext.Session.Remove("oauth_state");
var response = await httpClient.PostAsync($"{baseUrl}/oauth/token",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("grant_type", "authorization_code"),
new KeyValuePair<string,string>("code", code),
new KeyValuePair<string,string>("redirect_uri", redirectUri),
new KeyValuePair<string,string>("client_id", clientId),
new KeyValuePair<string,string>("code_verifier", codeVerifier),
}));
var body = await response.Content.ReadAsStringAsync();
// parse and store tokens...
}
Successful response (200 OK):
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
"token_type": "Bearer",
"expires_in": 900,
"refresh_token": "rt_aB3kPq7mN2xR8vT1...",
"scope": "api:read offline_access"
}
ℹ️ Store the access_token in memory (never in localStorage). Store the refresh_token in an httpOnly Secure cookie or server-side session.
Phase 4 — Refresh the Access Token
The access token expires after expires_in seconds (typically 15 minutes). Use the refresh token to get a new access token without requiring the user to log in again.
⚠️ Refresh token rotation is enforced. Each use of a refresh token issues a NEW refresh token and immediately invalidates the old one. Always save the new refresh_token from the response. If you reuse an old refresh token, the entire session is revoked and the user must log in again.
.NET:
var response = await httpClient.PostAsync($"{baseUrl}/oauth/token",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("grant_type", "refresh_token"),
new KeyValuePair<string,string>("refresh_token", currentRefreshToken),
new KeyValuePair<string,string>("client_id", clientId),
// No client_secret for public clients
}));
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
// Refresh token expired or replayed — user must log in again
ClearSession();
return Redirect(loginUrl);
}
// Save new access_token and new refresh_token from response
JavaScript:
const response = await fetch(`${baseUrl}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: currentRefreshToken,
client_id: clientId,
}),
});
if (!response.ok) {
// Refresh token expired or replayed — redirect to login
startLoginFlow();
return;
}
const data = await response.json();
// Save data.access_token and data.refresh_token (rotation!)
Logout — Revoking the Refresh Token
On logout, revoke the refresh token server-side to invalidate the session immediately.
.NET:
await httpClient.PostAsync($"{baseUrl}/oauth/revoke",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("token", refreshToken),
new KeyValuePair<string,string>("token_type_hint", "refresh_token"),
}));
// Always returns 200 OK, even if token is unknown
JavaScript:
await fetch(`${baseUrl}/oauth/revoke`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
token: refreshToken,
token_type_hint: "refresh_token",
}),
});
Token Introspection
If your application acts as a Resource Server and needs to verify a token it received, use the introspection endpoint. Note: if you are using JWT access tokens, you can also validate them locally by verifying the RS256 signature using the public keys from the JWKS endpoint.
Endpoint: POST {baseUrl}/oauth/introspect
ℹ️ The introspection endpoint requires the caller to authenticate with its own RS ClientId and ClientSecret (not the token owner’s credentials). Rate limit: 100 requests/min per RS client.
POST {baseUrl}/oauth/introspect
Authorization: Basic base64(rsClientId:rsClientSecret)
Content-Type: application/x-www-form-urlencoded
token=eyJhbGciOiJSUzI1NiIsImtpZCI6...
&token_type_hint=access_token
Active token response:
{
"active": true,
"scope": "api:read",
"client_id": "cc_ecommerce_01",
"sub": "user-123",
"exp": 1711370400,
"jti": "550e8400-...",
"cs_profile": "Contact Client"
}
Inactive / expired / revoked token:
{ "active": false }
⚠️ Always check active: true before using any other field. If active is false, all other fields are absent or meaningless.
JWT Validation (Resource Server)
Access tokens issued by Cirrus Shield are signed JWTs (RS256). If your application is a Resource Server, you can validate tokens locally without calling the introspection endpoint by verifying the signature using CS’s public keys.
JWKS endpoint: GET {baseUrl}/oauth/.well-known/jwks.json
The JWT payload contains the following claims:
| Claim | Description |
|---|---|
| iss | Issuer — the CS OAuth server URL |
| sub | Subject — client_id (Client Credentials) or user identifier (Auth Code) |
| aud | Audience — the CS API URL |
| iat | Issued at timestamp (Unix) |
| exp | Expiry timestamp (Unix) — reject if past |
| jti | Unique token ID — use for anti-replay checks |
| scope | Granted scopes, space-separated |
| client_id | The Connected App client_id |
| auth_mode | CLIENT_CREDENTIALS or AUTHORIZATION_CODE |
| cs_user_id | CS user associated with this token |
| cs_profile | CS profile of the associated user |
| cs_org_id | Organisation ID |
Validation checklist:
- Verify RS256 signature using the public key matching the kid header claim from JWKS
- Verify exp is in the future (allow up to 5 seconds clock skew)
- Verify iss matches your expected CS base URL
- Verify aud matches your API URL
- Verify jti is not in your revoked token list
- Verify the token has the required scope for the requested operation
ℹ️ During key rotation, CS publishes both the old and new public key simultaneously for at least 24 hours. Always use the kid claim to select the correct key rather than assuming a single key.
Scopes
Scopes control what data and operations an access token grants access to. Request only the scopes your application actually needs.
| Scope | Access Granted |
|---|---|
| api | Full access — read, write, and delete |
| api:read | Read-only access to CRM data |
| api:write | Create and update CRM data |
| api:delete | Delete CRM data |
| offline_access | Allows issuance of a refresh token (Authorization Code flow only) |
ℹ️ The scopes your token can request are limited by what was configured for your Connected App by the Cirrus Shield administrator. Requesting a scope not allowed for your app returns 400 invalid_scope.
Common Errors and Solutions
| Error | Cause | Solution |
|---|---|---|
| 401 invalid_client | Wrong ClientId or ClientSecret, or client disabled | Check credentials with your CS admin. Verify the client is active. |
| 400 invalid_scope | Requested scope not allowed for this client | Request only scopes configured for your Connected App. |
| 400 invalid_grant | Authorization code expired (>60s) or already used | Exchange the code immediately after receiving it in the callback. |
| 400 invalid_grant (code_verifier) | code_verifier does not match code_challenge | Ensure you stored the correct verifier and pass it unchanged. |
| 401 token_revoked | Refresh token expired (>7 days) or reused after rotation | Discard tokens and restart the login flow. |
| 403 ip_not_allowed | Request IP not in AllowedIPs for this client | Contact your CS admin to add your IP to the Connected App. |
| 429 Too Many Requests | Rate limit hit (10 token requests/min) | Implement token caching. Respect the Retry-After header. |
| 401 on API call | Token expired or revoked mid-session | Invalidate cached token, request a new one, retry the call once. |
Security Checklist
- Never log or expose ClientSecret, access tokens, or refresh tokens
- Never store tokens in localStorage or cookies accessible to JavaScript — use httpOnly Secure cookies or server-side session
- Always verify the state parameter in the OAuth callback before processing the code
- Always use PKCE (S256) — never use the plain method
- Always cache tokens and reuse them across requests — never request a new token per API call
- Always save the new refresh token after every refresh call — never reuse the old one
- Always send the access token in the Authorization: Bearer header — never in query parameters
- Always call /oauth/revoke on logout to invalidate the refresh token server-side
- Implement a single 401-retry: on 401, invalidate cached token, get a new one, retry once. If the retry also fails, surface the error.