Authentication¶
The SDK supports multiple authentication methods depending on your use case.
Coded Apps¶
Once your app is deployed as a Coded App, the platform injects all configuration automatically at deploy time. You can construct UiPath with no arguments — the SDK reads from the injected meta tags:
import { UiPath } from '@uipath/uipath-typescript/core';
const sdk = new UiPath();
await sdk.initialize();
See Coded Apps — Getting Started for the full setup guide.
OAuth Authentication (Recommended)¶
For OAuth, first create a non confidential External App.
- In UiPath Cloud: Admin → External Applications
- Click Add Application → Non Confidential Application
- Configure:
- Name: Your app name
- Redirect URI: For eg,
http://localhost:3000(for development) - Scopes: Select permissions you need (see scopes guide)
- Save and copy the Client ID
Add the Client ID and other config to your uipath.json. The @uipath/coded-apps-dev bundler plugin injects these as meta tags during local development; at deploy time the platform injects them automatically.
With config in place, initialize the SDK with no arguments — it reads everything from the injected meta tags:
import { UiPath } from '@uipath/uipath-typescript/core';
const sdk = new UiPath();
await sdk.initialize();
Token renewal¶
With OAuth sign-in, the SDK renews the access token about a minute before it expires, on the next request your app makes, so users stay signed in.
Enforcing sign-in through the organization's identity provider¶
By default users see the UiPath account sign-in screen. Set enforceSso: true to send them
straight to the organization's configured identity provider instead.
Only where everyone signs in through SSO
Users who sign in with a UiPath account do not exist in the organization's identity provider and will be rejected by it.
Organization name or id
orgName can be either the organization name or the organization id.
Secret-based Authentication¶
import { UiPath } from '@uipath/uipath-typescript/core';
const sdk = new UiPath({
baseUrl: 'https://api.uipath.com',
orgName: 'your-organization',
tenantName: 'your-tenant',
secret: 'your-secret' //PAT Token or Bearer Token
});
Using externally obtained tokens
If you have backend / external system that handles authentication and token generation, you can pass the token directly to the SDK via the secret parameter at initialization. When the token expires, your backend / external system can inject a refreshed token into the same instance via sdk.updateToken() to keep it authenticated. In this setup, token lifecycle management stays entirely on your side. In a deployed coded app the platform has already injected OAuth meta tags; passing secret still selects secret authentication and those injected fields are dropped.
To Generate a PAT Token:
- Log in to UiPath Cloud
- Go to User Profile → Preferences → Personal Access Token
- Click Create Token
- Give it a name and expiration date
- Provide relevant scopes
Confidential App-scoped External App (client-credentials)¶
You can also authenticate the SDK with a token issued to a confidential, app-scoped External App via the client-credentials grant. Your backend requests the token using the app's Client ID and Client Secret, then passes it to the SDK through the secret parameter — like any other bearer token above.
To create a confidential app-scoped External App:
- In UiPath Cloud: Admin → External Applications
- Click Add Application → Confidential Application
- Configure:
- Name: Your app name
- Scopes: Select the permissions you need (see scopes guide). All scopes must be added as Application scopes, not User scopes.
- Save and copy the Client ID and the Client Secret — you will not be shown the Client Secret again
- Follow the official UiPath documentation on how to request client-credentials tokens for a confidential app with application scopes
- Pass this token as your
secret, as shown in the Secret-based Authentication example above
Keep the Client Secret confidential
The Client Secret must never be exposed to public or client-side consumers. If it is exposed, revoke it immediately and generate a new one.
No refresh tokens
The client-credentials flow does not support refresh tokens. To refresh, request a new token directly using the External App's client-credentials.
Coded Functions¶
A coded function receives its platform coordinates as the handler's ctx. Pass
that straight to the SDK — it maps the context itself, so the handler names no
credential fields and never touches the workload token:
import { defineFunction } from '@uipath/coded-functions-js-sdk';
import { UiPath } from '@uipath/uipath-typescript/core';
import { Entities } from '@uipath/uipath-typescript/entities';
export default defineFunction({
name: 'list-entities',
handler: async (_input, ctx) => {
const sdk = new UiPath(ctx);
const entities = await new Entities(sdk).getAll();
return { entityCount: entities.length };
},
});
Construct the SDK inside the handler, once per invocation. A single instance hoisted to module scope would keep serving the org, tenant and token of whichever invocation created it.
The constructor reads ctx.platform — baseUrl, reduced to its origin, and the
orgId and tenantId GUIDs, which the platform accepts in place of names — and
ctx.robot.accessToken as the bearer token. ctx.platform.folderKey is the
fallback folder for a call that needs a folder and names none, such as a lookup
by name, which runs against the invocation's folder. Integration Service calls
are left unscoped: Integration Service rejects a connection outside the folder a
call names, and the connection a function uses often lives in another folder.
Explicit folderId, folderKey or folderPath options still win. On a local
run, where ctx.platform is null, the constructor
falls through to the environment contract below; when neither supplies a
coordinate, the error names it.
Server-side and scripts (environment contract)¶
Outside the browser — a script, a test, a CI job — the SDK configures itself
from environment variables, so new UiPath() needs no arguments:
UIPATH_BASE_URL=https://cloud.uipath.com
UIPATH_ORG_NAME=<organization> # an id works here as well as a name
UIPATH_TENANT_NAME=<tenant>
UIPATH_ACCESS_TOKEN=<accessToken> # PAT or bearer token
These are the names this SDK already uses elsewhere for the same values, so one
.env serves a script and a test run alike.
The variables are read from process.env or Deno.env, whichever the runtime
provides.
To state the configuration explicitly instead, pass it to the constructor — this takes precedence over both the environment and meta tags:
const sdk = new UiPath({
baseUrl: 'https://cloud.uipath.com',
orgName: '<organizationId>', // an id works here as well as a name
tenantName: '<tenantId>',
secret: '<accessToken>' // any bearer token
});
The access token is consumed internally and is never exposed on sdk.config.
Precedence
Constructor arguments win over meta tags, which win over the environment. Meta tags apply in the browser only; the environment contract applies outside it.
Precedence is per field, so a config passing only secret still inherits any
injected clientId, redirectUri and scope. Naming one method drops the
other's inherited fields. If the merge still carries secret beside a
complete OAuth set, the constructor throws, naming each field and its source.
SDK Initialization - The initialize() Method¶
When to Use initialize()¶
The initialize() method completes the authentication process for the SDK:
- Secret Authentication: Auto-initializes when creating the SDK instance - no need to call initialize(). This covers
secret,accessToken, a coded function'sctx, and the environment contract. - OAuth Authentication: MUST call
await sdk.initialize()before using any SDK services
Example: Secret Authentication (Auto-initialized)¶
import { UiPath } from '@uipath/uipath-typescript/core';
import { Tasks } from '@uipath/uipath-typescript/tasks';
const sdk = new UiPath({
baseUrl: 'https://api.uipath.com',
orgName: 'your-organization',
tenantName: 'your-tenant',
secret: 'your-secret' //PAT Token or Bearer Token
});
// Ready to use immediately - no initialize() needed
const tasks = new Tasks(sdk);
const allTasks = await tasks.getAll();
Example: OAuth Authentication (Requires initialize)¶
import { UiPath } from '@uipath/uipath-typescript/core';
import { Tasks } from '@uipath/uipath-typescript/tasks';
const sdk = new UiPath({
baseUrl: 'https://api.uipath.com',
orgName: 'your-organization',
tenantName: 'your-tenant',
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000',
scope: 'your-scopes'
});
// Must initialize before using services
try {
await sdk.initialize();
console.log('SDK initialized successfully');
// Now you can use the SDK
const tasks = new Tasks(sdk);
const allTasks = await tasks.getAll();
} catch (error) {
console.error('Failed to initialize SDK:', error);
}
OAuth Integration Patterns¶
Auto-login on App Load¶
import { UiPath } from '@uipath/uipath-typescript/core';
const sdk = new UiPath({...oauthConfig});
useEffect(() => {
const initSDK = async () => {
await sdk.initialize();
};
initSDK();
}, []);
User-Triggered Login¶
import { UiPath } from '@uipath/uipath-typescript/core';
const sdk = new UiPath({...oauthConfig});
const onLogin = async () => {
await sdk.initialize();
};
// Handle OAuth callback
const oauthCompleted = useRef(false);
useEffect(() => {
if (sdk.isInitialized() && !oauthCompleted.current) {
oauthCompleted.current = true;
sdk.completeOAuth();
}
}, []);
Using the token in your own requests¶
For requests your app makes outside the SDK, get the token from sdk.getValidToken(). It resolves with an access token that is valid right now and renews it first when needed, exactly as the SDK does for its own calls:
const token = await sdk.getValidToken();
const { baseUrl, orgName, tenantName } = sdk.config;
const response = await fetch(`${baseUrl}/${orgName}/${tenantName}/<servicePath>`, {
headers: { Authorization: `Bearer ${token}` }
});
Call it before each request instead of keeping the result. It answers from memory until a renewal is due, and calls made at the same time share one renewal. sdk.getToken() only reads the token the SDK holds and never renews it, so a token read from it can expire while your app still holds it.
The SDK renews the tokens of its own OAuth sign-in. A token you passed as secret is returned as it is: the SDK does not know when it expires and cannot renew it.
getValidToken() rejects with an AuthenticationError when it cannot return a token, for example before sign-in or when the renewal failed. A renewal can fail for a temporary reason such as a network error, so retry before calling sdk.initialize() to sign in again.
Available Auth Methods¶
sdk.initialize()- Start OAuth flow (auto completes also based on callback state)sdk.isInitialized()- Check if SDK initialization completedsdk.isAuthenticated()- Check if user has valid tokensdk.isInOAuthCallback()- Check if processing OAuth redirectsdk.completeOAuth()- Manually complete OAuth (advanced use)sdk.getToken()- Get the logged-in user's access tokensdk.logout()- Logout and clear all authentication state (requires re-initialization to authenticate again). By default the UiPath session (Automation Cloud or Automation Suite) stays active, so the next sign-in completes silently. Passsdk.logout({ endSession: true })to also sign the user out of UiPath session — the browser is redirected to end the session and returns to your app.sdk.updateToken()- Inject a refreshed token into the SDK instance (useful for backend services managing token lifecycle)sdk.getValidToken()- Get an access token that is valid right now, renewing it first when needed. Use it for requests your app makes outside the SDKsdk.setDebugContext()- Attach a parent job key to the jobs the app starts so Orchestrator links them to it and, when that parent is a debug run, routes them as debug sub-jobs. Studio Web debug sessions and Action Center debug tasks hand the key to the SDK themselves; call this only when another host runs the app inside a job
Quick Test Script¶
Create .env file:
# .env
UIPATH_BASE_URL=https://api.uipath.com
UIPATH_ORG_NAME=your-organization-name
UIPATH_TENANT_NAME=your-tenant-name
UIPATH_SECRET=your-pat-token
Verify your authentication setup:
// test-auth.ts
import 'dotenv/config';
import { UiPath } from '@uipath/uipath-typescript/core';
import { Assets } from '@uipath/uipath-typescript/assets';
async function testAuthentication() {
const sdk = new UiPath({
baseUrl: process.env.UIPATH_BASE_URL!,
orgName: process.env.UIPATH_ORG_NAME!,
tenantName: process.env.UIPATH_TENANT_NAME!,
secret: process.env.UIPATH_SECRET!
});
try {
// Test with a simple API call
const assets = new Assets(sdk);
const allAssets = await assets.getAll();
console.log('Authentication successful!');
console.log(`Connected to ${process.env.UIPATH_ORG_NAME}/${process.env.UIPATH_TENANT_NAME}`);
console.log(`Found ${allAssets.items.length} assets`);
} catch (error) {
console.error('Authentication failed:');
console.error(error.message);
}
}
testAuthentication();
Run it: npx ts-node test-auth.ts