@workos/authkit-session 0.0.1-alpha.1 → 0.0.1-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +415 -36
- package/dist/index.cjs +150 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -25
- package/dist/index.d.ts +28 -25
- package/dist/index.js +149 -103
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
- package/src/core/client/WorkOSLite.ts +10 -0
- package/src/core/client/types.ts +3 -21
- package/src/core/config/ConfigurationProvider.ts +41 -29
- package/src/core/config.ts +3 -6
- package/src/core/createAuthKitFactory.ts +79 -13
- package/src/core/errors.ts +1 -1
- package/src/core/session/SessionManager.ts +94 -84
- package/src/core/session/TokenManager.ts +1 -1
- package/src/core/session/types.ts +1 -1
- package/src/index.ts +1 -0
package/README.md
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
# @workos/authkit-session
|
|
2
2
|
|
|
3
3
|
> [!WARNING]
|
|
4
|
-
>This is prerelease software. APIs may change without notice.
|
|
4
|
+
> This is prerelease software. APIs may change without notice.
|
|
5
5
|
|
|
6
6
|
A framework-agnostic authentication library for WorkOS with a modular adapter system for server-side rendered applications.
|
|
7
7
|
|
|
8
|
+
This library serves as the foundation for framework-specific WorkOS authentication packages like `@workos-inc/authkit-nextjs`, `@workos-inc/authkit-remix`, and `@workos-inc/authkit-sveltekit`. By implementing the `SessionStorage` interface for your framework, you can provide WorkOS authentication capabilities with minimal framework-specific code.
|
|
9
|
+
|
|
8
10
|
## Features
|
|
9
11
|
|
|
10
12
|
- **Framework-agnostic core**: Common authentication logic that works across platforms
|
|
11
13
|
- **Adapter pattern**: Simple interface for framework-specific implementations
|
|
12
|
-
- **Session management**: Secure cookie-based authentication
|
|
14
|
+
- **Session management**: Secure encrypted cookie-based authentication
|
|
13
15
|
- **JWT handling**: Token validation, parsing, and refresh
|
|
14
|
-
- **
|
|
16
|
+
- **Organization switching**: Switch user context between organizations
|
|
17
|
+
- **Type-safe API**: Full TypeScript support with custom claims
|
|
18
|
+
- **Token claims parsing**: Extract and validate JWT claims
|
|
15
19
|
|
|
16
20
|
## Installation
|
|
17
21
|
|
|
@@ -44,36 +48,84 @@ configure({
|
|
|
44
48
|
2. Create a storage adapter for your framework:
|
|
45
49
|
|
|
46
50
|
```typescript
|
|
47
|
-
import {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
import {
|
|
52
|
+
createAuthKitFactory,
|
|
53
|
+
CookieSessionStorage,
|
|
54
|
+
} from '@workos/authkit-session';
|
|
55
|
+
import type {
|
|
56
|
+
SessionStorage,
|
|
57
|
+
ConfigurationProvider,
|
|
58
|
+
} from '@workos/authkit-session';
|
|
59
|
+
|
|
60
|
+
// Option 1: Extend CookieSessionStorage (recommended)
|
|
61
|
+
class MyFrameworkStorage extends CookieSessionStorage<MyRequest, MyResponse> {
|
|
62
|
+
constructor(config: ConfigurationProvider) {
|
|
63
|
+
super(config);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async getSession(request: MyRequest): Promise<string | null> {
|
|
67
|
+
// Extract cookie from your framework's request object
|
|
68
|
+
const cookies = request.headers.cookie || '';
|
|
69
|
+
const match = cookies.match(new RegExp(`${this.cookieName}=([^;]+)`));
|
|
70
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async saveSession(
|
|
74
|
+
response: MyResponse,
|
|
75
|
+
sessionData: string,
|
|
76
|
+
): Promise<MyResponse> {
|
|
77
|
+
// Set cookie on your framework's response object
|
|
78
|
+
const cookieValue = `${this.cookieName}=${encodeURIComponent(sessionData)}; ${this.getCookieAttributes()}`;
|
|
79
|
+
response.headers['Set-Cookie'] = cookieValue;
|
|
80
|
+
return response;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async clearSession(response: MyResponse): Promise<MyResponse> {
|
|
84
|
+
// Clear cookie by setting expired date
|
|
85
|
+
const expiredCookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
|
|
86
|
+
response.headers['Set-Cookie'] = expiredCookie;
|
|
87
|
+
return response;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private getCookieAttributes(): string {
|
|
91
|
+
const attrs = [];
|
|
92
|
+
if (this.cookieOptions.path) attrs.push(`path=${this.cookieOptions.path}`);
|
|
93
|
+
if (this.cookieOptions.domain)
|
|
94
|
+
attrs.push(`domain=${this.cookieOptions.domain}`);
|
|
95
|
+
if (this.cookieOptions.maxAge)
|
|
96
|
+
attrs.push(`max-age=${this.cookieOptions.maxAge}`);
|
|
97
|
+
if (this.cookieOptions.httpOnly) attrs.push('httponly');
|
|
98
|
+
if (this.cookieOptions.secure) attrs.push('secure');
|
|
99
|
+
if (this.cookieOptions.sameSite)
|
|
100
|
+
attrs.push(`samesite=${this.cookieOptions.sameSite}`);
|
|
101
|
+
return attrs.join('; ');
|
|
56
102
|
}
|
|
103
|
+
}
|
|
57
104
|
|
|
105
|
+
// Option 2: Implement SessionStorage interface directly
|
|
106
|
+
class CustomStorage implements SessionStorage<MyRequest, MyResponse> {
|
|
58
107
|
async getSession(request: MyRequest): Promise<string | null> {
|
|
59
|
-
//
|
|
60
|
-
return
|
|
108
|
+
// Your custom session retrieval logic
|
|
109
|
+
return getSessionFromRequest(request);
|
|
61
110
|
}
|
|
62
111
|
|
|
63
|
-
async saveSession(
|
|
64
|
-
|
|
65
|
-
|
|
112
|
+
async saveSession(
|
|
113
|
+
response: MyResponse,
|
|
114
|
+
sessionData: string,
|
|
115
|
+
): Promise<MyResponse> {
|
|
116
|
+
// Your custom session storage logic
|
|
117
|
+
return saveSessionToResponse(response, sessionData);
|
|
66
118
|
}
|
|
67
119
|
|
|
68
120
|
async clearSession(response: MyResponse): Promise<MyResponse> {
|
|
69
|
-
//
|
|
70
|
-
return
|
|
121
|
+
// Your custom session clearing logic
|
|
122
|
+
return clearSessionFromResponse(response);
|
|
71
123
|
}
|
|
72
124
|
}
|
|
73
125
|
|
|
74
126
|
// Create your AuthKit instance
|
|
75
127
|
const authKit = createAuthKitFactory<MyRequest, MyResponse>({
|
|
76
|
-
sessionStorageFactory:
|
|
128
|
+
sessionStorageFactory: config => new MyFrameworkStorage(config),
|
|
77
129
|
});
|
|
78
130
|
```
|
|
79
131
|
|
|
@@ -81,8 +133,11 @@ const authKit = createAuthKitFactory<MyRequest, MyResponse>({
|
|
|
81
133
|
|
|
82
134
|
```typescript
|
|
83
135
|
// Validate a session
|
|
84
|
-
const
|
|
85
|
-
|
|
136
|
+
const { user, claims, sessionId, impersonator, accessToken, refreshToken } =
|
|
137
|
+
await authKit.withAuth(request);
|
|
138
|
+
|
|
139
|
+
// Note: ensureSignedIn option not yet implemented
|
|
140
|
+
// Framework adapters should handle redirects when user is null
|
|
86
141
|
|
|
87
142
|
// Generate an authorization URL
|
|
88
143
|
const authUrl = await authKit.getAuthorizationUrl({
|
|
@@ -91,11 +146,112 @@ const authUrl = await authKit.getAuthorizationUrl({
|
|
|
91
146
|
screenHint: 'sign-in', // or 'sign-up'
|
|
92
147
|
});
|
|
93
148
|
|
|
94
|
-
//
|
|
95
|
-
const
|
|
96
|
-
|
|
149
|
+
// Generate sign-in/sign-up URLs
|
|
150
|
+
const signInUrl = await authKit.getSignInUrl({
|
|
151
|
+
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
152
|
+
});
|
|
153
|
+
const signUpUrl = await authKit.getSignUpUrl({
|
|
154
|
+
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Get token claims from current session
|
|
158
|
+
const claims = await authKit.getTokenClaims(request);
|
|
159
|
+
// Or parse specific access token
|
|
160
|
+
const specificClaims = await authKit.getTokenClaims(request, accessToken);
|
|
161
|
+
|
|
162
|
+
// Switch to different organization
|
|
163
|
+
const { response: updatedResponse, authResult: newAuth } =
|
|
164
|
+
await authKit.switchToOrganization(request, response, 'org_123');
|
|
165
|
+
|
|
166
|
+
// Handle OAuth callback
|
|
167
|
+
const {
|
|
168
|
+
response: updatedResponse,
|
|
169
|
+
returnPathname,
|
|
170
|
+
authResponse,
|
|
171
|
+
} = await authKit.handleCallback(request, response, {
|
|
172
|
+
code: 'oauth_code_from_query',
|
|
173
|
+
state: 'optional_state_from_query',
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// Sign out (simple session termination)
|
|
177
|
+
const clearedResponse = await authKit.signOut(request, response, {
|
|
178
|
+
returnTo: 'https://yourdomain.com',
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// Terminate session and get logout URL (advanced)
|
|
182
|
+
const { response: clearedResponse, logoutUrl } = await authKit.terminateSession(
|
|
183
|
+
session,
|
|
184
|
+
response,
|
|
185
|
+
{ returnTo: 'https://yourdomain.com' },
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
// Manually save a session (for custom auth flows)
|
|
189
|
+
await authKit.saveSession(response, authResponse);
|
|
190
|
+
|
|
191
|
+
// Manually refresh session
|
|
192
|
+
const refreshedAuth = await authKit.refreshSession(session, organizationId);
|
|
97
193
|
```
|
|
98
194
|
|
|
195
|
+
## For Framework Implementers
|
|
196
|
+
|
|
197
|
+
If you're building a framework-specific package (like `@workos-inc/authkit-sveltekit`), this library provides everything needed for WorkOS authentication:
|
|
198
|
+
|
|
199
|
+
### Implementation Steps
|
|
200
|
+
|
|
201
|
+
1. **Install and configure** `@workos/authkit-session` as a dependency
|
|
202
|
+
2. **Create a SessionStorage adapter** for your framework's request/response objects
|
|
203
|
+
3. **Export framework-specific helpers** that wrap the core AuthKit functionality
|
|
204
|
+
4. **Handle routing** for sign-in, callback, and sign-out endpoints
|
|
205
|
+
|
|
206
|
+
### Example Framework Package Structure
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
// src/storage.ts - Framework-specific storage adapter
|
|
210
|
+
import { CookieSessionStorage } from '@workos/authkit-session';
|
|
211
|
+
import type { ConfigurationProvider } from '@workos/authkit-session';
|
|
212
|
+
|
|
213
|
+
export class SvelteKitStorage extends CookieSessionStorage<RequestEvent, void> {
|
|
214
|
+
// Implement framework-specific cookie handling
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/index.ts - Main exports
|
|
218
|
+
import { configure, createAuthKitFactory } from '@workos/authkit-session';
|
|
219
|
+
import { SvelteKitStorage } from './storage';
|
|
220
|
+
|
|
221
|
+
export { configure };
|
|
222
|
+
|
|
223
|
+
export const authKit = createAuthKitFactory({
|
|
224
|
+
sessionStorageFactory: config => new SvelteKitStorage(config),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
// Framework-specific helpers
|
|
228
|
+
export async function withAuth(event: RequestEvent) {
|
|
229
|
+
return authKit.withAuth(event);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function handleCallback(event: RequestEvent) {
|
|
233
|
+
const url = new URL(event.request.url);
|
|
234
|
+
const code = url.searchParams.get('code');
|
|
235
|
+
const state = url.searchParams.get('state');
|
|
236
|
+
|
|
237
|
+
if (!code) throw new Error('Missing authorization code');
|
|
238
|
+
|
|
239
|
+
const result = await authKit.handleCallback(event, undefined, {
|
|
240
|
+
code,
|
|
241
|
+
state,
|
|
242
|
+
});
|
|
243
|
+
// Handle redirect to returnPathname
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### Key Considerations
|
|
248
|
+
|
|
249
|
+
- **Request/Response Objects**: Adapt your framework's request/response objects to the `SessionStorage` interface
|
|
250
|
+
- **Cookie Handling**: Implement secure cookie setting/getting for your framework
|
|
251
|
+
- **Routing Integration**: Provide helpers for authentication routes (`/auth/signin`, `/auth/callback`, `/auth/signout`)
|
|
252
|
+
- **TypeScript Support**: Export proper types for your framework's patterns
|
|
253
|
+
- **Error Handling**: Wrap AuthKit errors in framework-appropriate error types
|
|
254
|
+
|
|
99
255
|
## Core Concepts
|
|
100
256
|
|
|
101
257
|
### Session Management
|
|
@@ -109,17 +265,122 @@ AuthKit SSR uses encrypted cookies to store session information. It handles:
|
|
|
109
265
|
|
|
110
266
|
### Adapter System
|
|
111
267
|
|
|
112
|
-
|
|
268
|
+
AuthKit uses an adapter pattern to abstract framework-specific request/response handling. This allows the core authentication logic to remain framework-agnostic while enabling support for any server-side framework.
|
|
269
|
+
|
|
270
|
+
#### SessionStorage Interface
|
|
113
271
|
|
|
114
272
|
```typescript
|
|
115
273
|
interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
|
|
116
274
|
getSession(request: TRequest): Promise<string | null>;
|
|
117
|
-
saveSession(
|
|
275
|
+
saveSession(
|
|
276
|
+
response: TResponse,
|
|
277
|
+
sessionData: string,
|
|
278
|
+
options?: TOptions,
|
|
279
|
+
): Promise<TResponse>;
|
|
118
280
|
clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
|
|
119
281
|
}
|
|
120
282
|
```
|
|
121
283
|
|
|
122
|
-
|
|
284
|
+
#### CookieSessionStorage Base Class
|
|
285
|
+
|
|
286
|
+
For cookie-based session storage, extend the provided `CookieSessionStorage` class:
|
|
287
|
+
|
|
288
|
+
```typescript
|
|
289
|
+
import { CookieSessionStorage } from '@workos/authkit-session';
|
|
290
|
+
|
|
291
|
+
abstract class CookieSessionStorage<TRequest, TResponse> {
|
|
292
|
+
protected cookieName: string; // From config: cookieName
|
|
293
|
+
protected cookieOptions: CookieOptions; // Derived from config
|
|
294
|
+
|
|
295
|
+
// Implement these methods for your framework
|
|
296
|
+
abstract getSession(request: TRequest): Promise<string | null>;
|
|
297
|
+
abstract saveSession(
|
|
298
|
+
response: TResponse,
|
|
299
|
+
sessionData: string,
|
|
300
|
+
): Promise<TResponse>;
|
|
301
|
+
abstract clearSession(response: TResponse): Promise<TResponse>;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
interface CookieOptions {
|
|
305
|
+
path?: string; // Default: '/'
|
|
306
|
+
domain?: string; // From config: cookieDomain
|
|
307
|
+
maxAge?: number; // From config: cookieMaxAge (400 days)
|
|
308
|
+
httpOnly?: boolean; // Default: true
|
|
309
|
+
secure?: boolean; // From config: apiHttps
|
|
310
|
+
sameSite?: 'lax' | 'strict' | 'none'; // From config: cookieSameSite
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
#### Framework-Specific Examples
|
|
315
|
+
|
|
316
|
+
**Express/Node.js:**
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
class ExpressStorage extends CookieSessionStorage<Request, Response> {
|
|
320
|
+
async getSession(request: Request): Promise<string | null> {
|
|
321
|
+
return request.cookies[this.cookieName] || null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async saveSession(
|
|
325
|
+
response: Response,
|
|
326
|
+
sessionData: string,
|
|
327
|
+
): Promise<Response> {
|
|
328
|
+
response.cookie(this.cookieName, sessionData, this.cookieOptions);
|
|
329
|
+
return response;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async clearSession(response: Response): Promise<Response> {
|
|
333
|
+
response.clearCookie(this.cookieName, { path: this.cookieOptions.path });
|
|
334
|
+
return response;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
**Hono:**
|
|
340
|
+
|
|
341
|
+
```typescript
|
|
342
|
+
class HonoStorage extends CookieSessionStorage<HonoRequest, HonoResponse> {
|
|
343
|
+
async getSession(request: HonoRequest): Promise<string | null> {
|
|
344
|
+
return getCookie(request, this.cookieName) || null;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async saveSession(
|
|
348
|
+
response: HonoResponse,
|
|
349
|
+
sessionData: string,
|
|
350
|
+
): Promise<HonoResponse> {
|
|
351
|
+
setCookie(response, this.cookieName, sessionData, this.cookieOptions);
|
|
352
|
+
return response;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async clearSession(response: HonoResponse): Promise<HonoResponse> {
|
|
356
|
+
deleteCookie(response, this.cookieName);
|
|
357
|
+
return response;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
#### Creating Framework Adapters
|
|
363
|
+
|
|
364
|
+
When creating an adapter for a new framework:
|
|
365
|
+
|
|
366
|
+
1. **Choose your approach**: Extend `CookieSessionStorage` for cookie-based storage, or implement `SessionStorage` directly for custom storage
|
|
367
|
+
2. **Handle framework request/response objects**: Extract cookies from requests and set cookies on responses
|
|
368
|
+
3. **Respect configuration**: Use `this.cookieName` and `this.cookieOptions` from the base class
|
|
369
|
+
4. **Test thoroughly**: Ensure session persistence works across requests
|
|
370
|
+
|
|
371
|
+
#### Factory Configuration
|
|
372
|
+
|
|
373
|
+
```typescript
|
|
374
|
+
const authKit = createAuthKitFactory<MyRequest, MyResponse>({
|
|
375
|
+
sessionStorageFactory: config => new MyFrameworkStorage(config),
|
|
376
|
+
|
|
377
|
+
// Optional: Custom session encryption
|
|
378
|
+
sessionEncryptionFactory: config => myCustomEncryption,
|
|
379
|
+
|
|
380
|
+
// Optional: Custom WorkOS client
|
|
381
|
+
clientFactory: config => myCustomWorkOSClient,
|
|
382
|
+
});
|
|
383
|
+
```
|
|
123
384
|
|
|
124
385
|
## Configuration
|
|
125
386
|
|
|
@@ -132,6 +393,11 @@ WORKOS_CLIENT_ID=your-client-id
|
|
|
132
393
|
WORKOS_API_KEY=your-api-key
|
|
133
394
|
WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
|
|
134
395
|
WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long
|
|
396
|
+
WORKOS_COOKIE_NAME=wos-session
|
|
397
|
+
WORKOS_COOKIE_MAX_AGE=34560000
|
|
398
|
+
WORKOS_API_HOSTNAME=api.workos.com
|
|
399
|
+
WORKOS_API_HTTPS=true
|
|
400
|
+
WORKOS_API_PORT=443
|
|
135
401
|
```
|
|
136
402
|
|
|
137
403
|
### Programmatic Configuration
|
|
@@ -144,9 +410,13 @@ configure({
|
|
|
144
410
|
apiKey: 'your-api-key',
|
|
145
411
|
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
146
412
|
cookiePassword: 'must-be-at-least-32-characters-long',
|
|
147
|
-
cookieName: '
|
|
148
|
-
cookieMaxAge: 60 * 60 * 24 *
|
|
413
|
+
cookieName: 'wos-session', // Default: 'wos-session'
|
|
414
|
+
cookieMaxAge: 60 * 60 * 24 * 400, // 400 days in seconds
|
|
149
415
|
cookieSameSite: 'lax', // 'strict', 'lax', or 'none'
|
|
416
|
+
cookieDomain: '.yourdomain.com', // Optional: cookie domain
|
|
417
|
+
apiHostname: 'api.workos.com', // Optional: API hostname
|
|
418
|
+
apiHttps: true, // Default: true
|
|
419
|
+
apiPort: 443, // Optional: API port
|
|
150
420
|
});
|
|
151
421
|
```
|
|
152
422
|
|
|
@@ -160,13 +430,122 @@ configure({
|
|
|
160
430
|
|
|
161
431
|
### AuthKit Instance API
|
|
162
432
|
|
|
163
|
-
|
|
433
|
+
#### Authentication & Session Management
|
|
434
|
+
|
|
435
|
+
- `withAuth<TCustomClaims>(request, options?)`: Validate the current session and return `AuthResult<TCustomClaims>`
|
|
436
|
+
- Note: `ensureSignedIn` option not yet implemented - framework adapters should handle redirects
|
|
437
|
+
- `handleCallback(request, response, { code, state? })`: Process OAuth callback and create session
|
|
438
|
+
- `signOut(request, response, options?)`: Simple session termination with cookie clearing
|
|
439
|
+
- `terminateSession(session, response, options?)`: Advanced session termination with logout URL
|
|
440
|
+
- `saveSession(response, authResponse)`: Manually save session from `AuthenticationResponse`
|
|
441
|
+
- `refreshSession(session, organizationId?)`: Manually refresh session tokens
|
|
442
|
+
|
|
443
|
+
#### URL Generation
|
|
444
|
+
|
|
164
445
|
- `getAuthorizationUrl(options)`: Generate a WorkOS authorization URL with `returnPathname`, `redirectUri`, and `screenHint`
|
|
165
|
-
- `getSignInUrl(options)`: Generate a sign-in URL
|
|
166
|
-
- `getSignUpUrl(options)`: Generate a sign-up URL
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
446
|
+
- `getSignInUrl(options)`: Generate a sign-in URL with `organizationId`, `loginHint`, and `redirectUri`
|
|
447
|
+
- `getSignUpUrl(options)`: Generate a sign-up URL with `organizationId`, `loginHint`, and `redirectUri`
|
|
448
|
+
|
|
449
|
+
#### Token & Organization Management
|
|
450
|
+
|
|
451
|
+
- `getTokenClaims<TCustomClaims>(request, accessToken?)`: Parse JWT token claims from session or specific token
|
|
452
|
+
- `switchToOrganization(request, response, organizationId)`: Switch user to different organization context
|
|
453
|
+
|
|
454
|
+
## Advanced Features
|
|
455
|
+
|
|
456
|
+
### Organization Switching
|
|
457
|
+
|
|
458
|
+
Switch users between organizations without requiring re-authentication:
|
|
459
|
+
|
|
460
|
+
```typescript
|
|
461
|
+
try {
|
|
462
|
+
const { response: updatedResponse, authResult } =
|
|
463
|
+
await authKit.switchToOrganization(
|
|
464
|
+
request,
|
|
465
|
+
response,
|
|
466
|
+
'org_new_organization_id',
|
|
467
|
+
);
|
|
468
|
+
|
|
469
|
+
// Use the updated response and new auth context
|
|
470
|
+
const { user, sessionId, claims } = authResult;
|
|
471
|
+
} catch (error) {
|
|
472
|
+
if (error.authUrl) {
|
|
473
|
+
// Handle cases requiring re-authentication (SSO, MFA)
|
|
474
|
+
redirect(error.authUrl);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
### Token Claims Parsing
|
|
480
|
+
|
|
481
|
+
Extract and validate JWT claims from access tokens:
|
|
482
|
+
|
|
483
|
+
```typescript
|
|
484
|
+
// Parse claims from current session
|
|
485
|
+
const claims = await authKit.getTokenClaims<MyCustomClaims>(request);
|
|
486
|
+
|
|
487
|
+
// Parse claims from specific token
|
|
488
|
+
const specificClaims = await authKit.getTokenClaims<MyCustomClaims>(
|
|
489
|
+
request,
|
|
490
|
+
accessToken,
|
|
491
|
+
);
|
|
492
|
+
|
|
493
|
+
// Custom claims interface
|
|
494
|
+
interface MyCustomClaims {
|
|
495
|
+
custom_field: string;
|
|
496
|
+
user_metadata: Record<string, unknown>;
|
|
497
|
+
}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
### TypeScript Support
|
|
501
|
+
|
|
502
|
+
AuthKit provides full TypeScript support with generic type parameters:
|
|
503
|
+
|
|
504
|
+
```typescript
|
|
505
|
+
interface CustomClaims {
|
|
506
|
+
department: string;
|
|
507
|
+
permissions: string[];
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const { user, claims } = await authKit.withAuth<CustomClaims>(request);
|
|
511
|
+
// claims is typed as BaseTokenClaims & CustomClaims
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
### AuthResult Interface
|
|
515
|
+
|
|
516
|
+
The `withAuth` method returns an `AuthResult` object with the following structure:
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
interface AuthResult<TCustomClaims = Record<string, unknown>> {
|
|
520
|
+
user?: User | null; // WorkOS user object
|
|
521
|
+
claims?: BaseTokenClaims & TCustomClaims; // JWT token claims
|
|
522
|
+
impersonator?: Impersonator; // Impersonation context if any
|
|
523
|
+
accessToken?: string; // JWT access token
|
|
524
|
+
refreshToken?: string; // Refresh token
|
|
525
|
+
sessionId?: string; // Session identifier from claims
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
interface BaseTokenClaims {
|
|
529
|
+
sid: string; // Session ID
|
|
530
|
+
org_id?: string; // Organization ID
|
|
531
|
+
role?: string; // User role
|
|
532
|
+
permissions?: string[]; // User permissions
|
|
533
|
+
entitlements?: string[]; // User entitlements
|
|
534
|
+
feature_flags?: string[]; // Feature flags
|
|
535
|
+
}
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
### Additional Exports
|
|
539
|
+
|
|
540
|
+
The library also exports these components for advanced use cases:
|
|
541
|
+
|
|
542
|
+
```typescript
|
|
543
|
+
import {
|
|
544
|
+
SessionManager, // Core session management class
|
|
545
|
+
CookieSessionStorage, // Abstract cookie storage base class
|
|
546
|
+
getWorkOS, // WorkOS client factory
|
|
547
|
+
} from '@workos/authkit-session';
|
|
548
|
+
```
|
|
170
549
|
|
|
171
550
|
## Security
|
|
172
551
|
|