Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/connect/connect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,56 @@ function expectConnectApplication(result: any) {
describe('Connect', () => {
beforeEach(() => fetch.resetMocks());

describe('getAuthorizationUrl', () => {
it('builds the issuer authorize URL with organization_id', () => {
const url = workos.connect.getAuthorizationUrl({
issuer: 'https://auth.example.com/',
clientId: 'client_123',
redirectUri: 'https://app.example.com/callback',
organizationId: 'org_01EHZNVPK3SFK441A1RGBFSHRT',
scope: 'openid profile',
resource: 'https://mcp.example.com',
state: 'abc',
});

const parsed = new URL(url);
expect(parsed.origin + parsed.pathname).toBe(
'https://auth.example.com/oauth2/authorize',
);
expect(Object.fromEntries(parsed.searchParams)).toEqual({
client_id: 'client_123',
organization_id: 'org_01EHZNVPK3SFK441A1RGBFSHRT',
redirect_uri: 'https://app.example.com/callback',
resource: 'https://mcp.example.com',
response_type: 'code',
scope: 'openid profile',
state: 'abc',
});
});
});

describe('getAuthorizationUrlWithPKCE', () => {
it('adds an S256 challenge for the returned code verifier', async () => {
const { url, state, codeVerifier } =
await workos.connect.getAuthorizationUrlWithPKCE({
issuer: 'https://auth.example.com',
clientId: 'client_123',
redirectUri: 'myapp://callback',
organizationId: 'org_01EHZNVPK3SFK441A1RGBFSHRT',
});

const params = new URL(url).searchParams;
expect(params.get('state')).toBe(state);
expect(params.get('code_challenge_method')).toBe('S256');
expect(params.get('code_challenge')).toBe(
await workos.pkce.generateCodeChallenge(codeVerifier),
);
expect(params.get('organization_id')).toBe(
'org_01EHZNVPK3SFK441A1RGBFSHRT',
);
});
});

describe('exchangeToken', () => {
it('posts an RFC 8693 token exchange to the issuer and deserializes the response', async () => {
fetchOnce({
Expand Down
76 changes: 76 additions & 0 deletions src/connect/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ import type {
TokenExchangeResponse,
TokenExchangeResponseResponse,
} from './interfaces/token-exchange.interface';
import type {
ConnectAuthorizationURLOptions,
ConnectPKCEAuthorizationURLResult,
} from './interfaces/connect-authorization-url-options.interface';
import { toQueryString } from '../common/utils/query-string';
import { deserializeTokenExchangeResponse } from './serializers/token-exchange-response.serializer';
// @oagen-ignore-end
import { deserializeConnectApplication } from './serializers/connect-application.serializer';
Expand Down Expand Up @@ -110,6 +115,77 @@ export class Connect {
}

// @oagen-ignore-start
/**
* Generate an authorization URL for a Connect Application.
*
* Points at the environment's `${issuer}/oauth2/authorize` endpoint (AuthKit domain), not the WorkOS API.
* Pass `organizationId` to scope the authorization to one organization: the organization picker is skipped,
* and a user who isn't an active member is redirected to `redirectUri` with `error=access_denied`.
*
* Public clients should use `getAuthorizationUrlWithPKCE()` instead.
* @param options - Object containing issuer, clientId, redirectUri and optional authorization parameters.
* @returns {string} The authorization URL.
*/
getAuthorizationUrl(options: ConnectAuthorizationURLOptions): string {
const {
issuer,
clientId,
redirectUri,
scope,
state,
nonce,
organizationId,
loginHint,
prompt,
resource,
codeChallenge,
codeChallengeMethod,
} = options;

const query = toQueryString({
client_id: clientId,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
login_hint: loginHint,
nonce,
organization_id: organizationId,
prompt,
redirect_uri: redirectUri,
resource,
response_type: 'code',
scope,
state,
});

return `${issuer.replace(/\/+$/, '')}/oauth2/authorize?${query}`;
}

/**
* Generate an authorization URL for a Connect Application with PKCE.
*
* Generates the code verifier, S256 code challenge and `state`, and returns them with the URL. Store
* `codeVerifier` and `state` until the callback.
* @param options - Same as `getAuthorizationUrl()`, without the PKCE parameters and `state`.
* @returns {Promise<ConnectPKCEAuthorizationURLResult>} The URL, state and code verifier.
*/
async getAuthorizationUrlWithPKCE(
options: Omit<
ConnectAuthorizationURLOptions,
'codeChallenge' | 'codeChallengeMethod' | 'state'
>,
): Promise<ConnectPKCEAuthorizationURLResult> {
const pkce = await this.workos.pkce.generate();
const state = this.workos.pkce.generateCodeVerifier(43);
const url = this.getAuthorizationUrl({
...options,
state,
codeChallenge: pkce.codeChallenge,
codeChallengeMethod: 'S256',
});

return { url, state, codeVerifier: pkce.codeVerifier };
}

/**
* Exchange an access token for one issued to another Resource Indicator
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export interface ConnectAuthorizationURLOptions {
/**
* The OpenID issuer of the environment, e.g. `https://auth.example.com` or
* `https://<env>.authkit.app`. The URL points at `${issuer}/oauth2/authorize`.
*/
issuer: string;
/** Client ID of the Connect Application. */
clientId: string;
/** The URL to redirect the user to after they authorize. */
redirectUri: string;
/** Space-separated scopes to request, e.g. `openid profile email offline_access`. */
scope?: string;
/** An opaque value returned unchanged to `redirectUri`. */
state?: string;
/** A random value echoed in the ID token to mitigate replay attacks. */
nonce?: string;
/**
* The ID of the organization to scope the authorization to. The organization
* picker is skipped; a user who isn't an active member of the organization
* is redirected to `redirectUri` with `error=access_denied`.
*/
organizationId?: string;
/** Pre-fills the email address on the AuthKit sign-in page. */
loginHint?: string;
/** Space-separated `prompt` values, e.g. `login` or `consent`. */
prompt?: string;
/** Resource Indicator (RFC 8707) the access token should be issued for. */
resource?: string;
/** PKCE code challenge derived from a code verifier. */
codeChallenge?: string;
/** The PKCE code challenge method. Only `S256` is supported. */
codeChallengeMethod?: 'S256';
}

export interface ConnectPKCEAuthorizationURLResult {
/** The authorization URL to redirect the user to. */
url: string;
/** The generated `state` value. Verify it on the callback. */
state: string;
/** The PKCE code verifier. Store it and send it when exchanging the code. */
codeVerifier: string;
}
1 change: 1 addition & 0 deletions src/connect/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ export * from './user-consent-option-choice.interface';
export * from './user-consent-option.interface';
export * from './user-management-login-request.interface';
export * from './user-object.interface';
export * from './connect-authorization-url-options.interface';
export * from './token-exchange.interface';