@cas-system/react-cas-client 1.0.0

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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +449 -0
  3. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 InSol-2021
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,449 @@
1
+ # @cas-system/react-cas-client
2
+
3
+ React SDK for integrating with the **One System CAS (Central Authentication System)** server. Provides hooks, components, and a context provider for seamless SSO authentication in React 18+ applications.
4
+
5
+ ## Features
6
+
7
+ - 🔐 **SSO Login Flow** — Redirect-based login via the CAS server
8
+ - 🛡️ **Secure by Design** — Token validation is always delegated to your backend; secrets never reach the browser
9
+ - ⚛️ **React 18+ Hooks & Context** — `useCasAuth`, `useCasUser`, and `<CasProvider>`
10
+ - 🚪 **Route Protection** — `<CasProtectedRoute>` with role-based access control
11
+ - 🌳 **Tree-Shakeable** — Named exports only, `sideEffects: false`
12
+ - 📦 **Zero Dependencies** — Only peer-depends on `react >=18.2`
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @cas-system/react-cas-client
20
+ # or
21
+ yarn add @cas-system/react-cas-client
22
+ # or
23
+ pnpm add @cas-system/react-cas-client
24
+ ```
25
+
26
+ > **Peer dependency:** `react >= 18.2`
27
+
28
+ ### Compatibility
29
+
30
+ | Requirement | Version |
31
+ | ---------------- | ---------------------------------------------- |
32
+ | React (peer) | `>= 18.2` |
33
+ | Package version | `1.0.0` |
34
+ | Built with | TypeScript `6.x` |
35
+ | Reference sample | Vite `6`, React `18.3`, Node `20` |
36
+
37
+ ---
38
+
39
+ ## Quick Start
40
+
41
+ ### 1. Wrap your app with `<CasProvider>`
42
+
43
+ ```tsx
44
+ import { CasProvider } from '@cas-system/react-cas-client';
45
+
46
+ const casConfig = {
47
+ serverUrl: 'https://cas.example.com',
48
+ clientId: 'my-app',
49
+ callbackUrl: 'https://myapp.com/auth/callback',
50
+ backendValidateUrl: '/api/auth/validate',
51
+ };
52
+
53
+ function App() {
54
+ return (
55
+ <CasProvider
56
+ config={casConfig}
57
+ onAuthSuccess={(user) => console.log('Welcome,', user.username)}
58
+ onAuthError={(err) => console.error('Auth failed:', err)}
59
+ >
60
+ <YourApp />
61
+ </CasProvider>
62
+ );
63
+ }
64
+ ```
65
+
66
+ ### 2. Use hooks in any component
67
+
68
+ ```tsx
69
+ import { useCasAuth } from '@cas-system/react-cas-client';
70
+
71
+ function Header() {
72
+ const { user, isAuthenticated, isLoading, login, logout } = useCasAuth();
73
+
74
+ if (isLoading) return <p>Loading…</p>;
75
+
76
+ if (!isAuthenticated) {
77
+ return <button onClick={() => login()}>Sign in</button>;
78
+ }
79
+
80
+ return (
81
+ <div>
82
+ Welcome, {user?.username}!
83
+ <button onClick={() => logout()}>Sign out</button>
84
+ </div>
85
+ );
86
+ }
87
+ ```
88
+
89
+ ### 3. Protect routes
90
+
91
+ ```tsx
92
+ import { CasProtectedRoute } from '@cas-system/react-cas-client';
93
+
94
+ function AppRoutes() {
95
+ return (
96
+ <Routes>
97
+ <Route path="/" element={<HomePage />} />
98
+ <Route
99
+ path="/dashboard"
100
+ element={
101
+ <CasProtectedRoute fallback={<Spinner />}>
102
+ <Dashboard />
103
+ </CasProtectedRoute>
104
+ }
105
+ />
106
+ <Route
107
+ path="/admin"
108
+ element={
109
+ <CasProtectedRoute
110
+ roles={['admin']}
111
+ unauthorizedComponent={<Forbidden />}
112
+ fallback={<Spinner />}
113
+ >
114
+ <AdminPanel />
115
+ </CasProtectedRoute>
116
+ }
117
+ />
118
+ </Routes>
119
+ );
120
+ }
121
+ ```
122
+
123
+ ---
124
+
125
+ ## How It Works
126
+
127
+ ```
128
+ ┌──────────┐ 1. login() ┌────────────┐
129
+ │ React │ ──────────────────► │ CAS Server │
130
+ │ App │ │ /sso/login │
131
+ └──────────┘ └─────┬──────┘
132
+ ▲ │
133
+ │ 4. User + session established │ 2. User authenticates
134
+ │ │
135
+ ┌────┴─────┐ 3. POST /validate ┌────▼──────┐
136
+ │ React │ ◄────────────────── │ Your │
137
+ │ App │ ──────────────────► │ Backend │
138
+ │ callback │ { token } │ │
139
+ └──────────┘ └───────────┘
140
+ ```
141
+
142
+ 1. **`login()`** redirects the browser to the CAS SSO login page.
143
+ 2. The user authenticates on the CAS server.
144
+ 3. CAS redirects back to your `callbackUrl` with `?token=JWT_TOKEN`.
145
+ 4. `<CasProvider>` automatically extracts the token and sends it to your backend (`backendValidateUrl`) for validation.
146
+ 5. Your backend calls `POST {casServerUrl}/api/validate-token` with `{ token, client_id, client_secret }` and returns the user object.
147
+ 6. The SDK stores the user in `sessionStorage` and updates React state.
148
+
149
+ > **Security:** The `client_secret` never leaves your backend. The browser only sends the JWT to *your* backend, which proxies the validation request.
150
+
151
+ ---
152
+
153
+ ## Configuration
154
+
155
+ ### `CasConfig`
156
+
157
+ | Property | Type | Required | Description |
158
+ | -------------------- | -------- | -------- | --------------------------------------------------------------------------- |
159
+ | `serverUrl` | `string` | ✅ | Base URL of the CAS server (no trailing slash) |
160
+ | `clientId` | `string` | ✅ | OAuth client ID registered with the CAS server |
161
+ | `callbackUrl` | `string` | No | URL the CAS server redirects to after login. Defaults to current page URL. |
162
+ | `backendValidateUrl` | `string` | No | Your backend endpoint for token validation (e.g. `/api/auth/validate`) |
163
+
164
+ ---
165
+
166
+ ## API Reference
167
+
168
+ ### Provider
169
+
170
+ #### `<CasProvider>`
171
+
172
+ Wrap your app to provide CAS authentication context.
173
+
174
+ | Prop | Type | Description |
175
+ | --------------- | ------------------------- | ----------------------------------------- |
176
+ | `config` | `CasConfig` | CAS configuration (required) |
177
+ | `children` | `ReactNode` | Child components |
178
+ | `onAuthSuccess` | `(user: CasUser) => void` | Callback after successful authentication |
179
+ | `onAuthError` | `(error: string) => void` | Callback when authentication fails |
180
+
181
+ ---
182
+
183
+ ### Hooks
184
+
185
+ #### `useCasAuth()`
186
+
187
+ Returns the full authentication state and actions.
188
+
189
+ ```ts
190
+ const {
191
+ user, // CasUser | null
192
+ isAuthenticated, // boolean
193
+ isLoading, // boolean
194
+ error, // string | null
195
+ login, // (returnUrl?: string) => void
196
+ logout, // (redirectUrl?: string) => Promise<void>
197
+ hasRole, // (role: string) => boolean
198
+ hasAnyRole, // (roles: string[]) => boolean
199
+ } = useCasAuth();
200
+ ```
201
+
202
+ #### `useCasUser()`
203
+
204
+ Returns just user data and role helpers (no login/logout actions).
205
+
206
+ ```ts
207
+ const {
208
+ user, // CasUser | null
209
+ isAuthenticated, // boolean
210
+ isLoading, // boolean
211
+ hasRole, // (role: string) => boolean
212
+ hasAnyRole, // (roles: string[]) => boolean
213
+ hasAllRoles, // (roles: string[]) => boolean
214
+ } = useCasUser();
215
+ ```
216
+
217
+ ---
218
+
219
+ ### Components
220
+
221
+ #### `<CasProtectedRoute>`
222
+
223
+ Protects children behind authentication. Redirects to CAS login if unauthenticated.
224
+
225
+ | Prop | Type | Description |
226
+ | ----------------------- | ----------- | ----------------------------------------------------- |
227
+ | `children` | `ReactNode` | Content to render when authenticated |
228
+ | `fallback` | `ReactNode` | Loading component (default: `null`) |
229
+ | `roles` | `string[]` | Required roles (user needs at least one) |
230
+ | `unauthorizedComponent` | `ReactNode` | Shown when user lacks roles (otherwise redirects) |
231
+
232
+ #### `<CasLoginButton>`
233
+
234
+ A button that triggers CAS login on click. Accepts all standard `<button>` attributes.
235
+
236
+ | Prop | Type | Description |
237
+ | ----------- | ----------- | ---------------------------------------------- |
238
+ | `returnUrl` | `string` | URL to return to after login |
239
+ | `className` | `string` | CSS class name(s) |
240
+ | `children` | `ReactNode` | Button content (default: `"Sign in"`) |
241
+ | `...rest` | `ButtonHTMLAttributes` | Any standard button HTML attribute |
242
+
243
+ ```tsx
244
+ <CasLoginButton className="btn btn-primary">
245
+ 🔑 Log in with SSO
246
+ </CasLoginButton>
247
+ ```
248
+
249
+ ---
250
+
251
+ ### Core Client
252
+
253
+ #### `CasClient`
254
+
255
+ Low-level client class for advanced use cases. Most users should use the hooks/provider instead.
256
+
257
+ ```ts
258
+ import { CasClient } from '@cas-system/react-cas-client';
259
+
260
+ const client = new CasClient({
261
+ serverUrl: 'https://cas.example.com',
262
+ clientId: 'my-app',
263
+ backendValidateUrl: '/api/auth/validate',
264
+ });
265
+
266
+ // Build login URL
267
+ const url = client.getLoginUrl('/dashboard');
268
+
269
+ // Redirect to CAS login
270
+ client.login();
271
+
272
+ // Extract token from callback URL
273
+ const token = client.extractTokenFromUrl();
274
+
275
+ // Validate token via backend
276
+ const user = await client.validateTokenViaBackend(token);
277
+
278
+ // Full callback flow (extract + validate + store + clean URL)
279
+ const user = await client.handleCallback();
280
+
281
+ // Session management
282
+ client.getUser(); // CasUser | null
283
+ client.getToken(); // string | null
284
+ client.isAuthenticated(); // boolean
285
+
286
+ // Logout
287
+ await client.logout('/login');
288
+
289
+ // Role checks
290
+ client.userHasRole('admin');
291
+ client.userHasAnyRole(['admin', 'editor']);
292
+ client.userHasAllRoles(['admin', 'editor']);
293
+ ```
294
+
295
+ ---
296
+
297
+ ## Types
298
+
299
+ ### `CasUser`
300
+
301
+ ```ts
302
+ interface CasUser {
303
+ id: string;
304
+ username: string;
305
+ email: string;
306
+ roles?: string[];
307
+ }
308
+ ```
309
+
310
+ ### `CasAuthState`
311
+
312
+ ```ts
313
+ interface CasAuthState {
314
+ user: CasUser | null;
315
+ isAuthenticated: boolean;
316
+ isLoading: boolean;
317
+ error: string | null;
318
+ }
319
+ ```
320
+
321
+ ---
322
+
323
+ ## Examples
324
+
325
+ ### Custom Login Flow
326
+
327
+ ```tsx
328
+ import { useCasAuth } from '@cas-system/react-cas-client';
329
+
330
+ function LoginPage() {
331
+ const { login, isAuthenticated, error } = useCasAuth();
332
+
333
+ if (isAuthenticated) {
334
+ return <Navigate to="/dashboard" />;
335
+ }
336
+
337
+ return (
338
+ <div className="login-page">
339
+ <h1>Welcome</h1>
340
+ {error && <p className="error">{error}</p>}
341
+ <button onClick={() => login('/dashboard')}>
342
+ Sign in with SSO
343
+ </button>
344
+ </div>
345
+ );
346
+ }
347
+ ```
348
+
349
+ ### Role-Based UI
350
+
351
+ ```tsx
352
+ import { useCasUser } from '@cas-system/react-cas-client';
353
+
354
+ function Sidebar() {
355
+ const { user, hasRole, hasAnyRole } = useCasUser();
356
+
357
+ return (
358
+ <nav>
359
+ <a href="/dashboard">Dashboard</a>
360
+ {hasAnyRole(['admin', 'manager']) && (
361
+ <a href="/reports">Reports</a>
362
+ )}
363
+ {hasRole('admin') && (
364
+ <a href="/admin">Admin Panel</a>
365
+ )}
366
+ </nav>
367
+ );
368
+ }
369
+ ```
370
+
371
+ ### Backend Validate Endpoint (Express Example)
372
+
373
+ Your backend needs an endpoint that proxies token validation:
374
+
375
+ ```ts
376
+ // server/routes/auth.ts
377
+ app.post('/api/auth/validate', async (req, res) => {
378
+ const { token } = req.body;
379
+
380
+ const response = await fetch(`${CAS_SERVER_URL}/api/validate-token`, {
381
+ method: 'POST',
382
+ headers: { 'Content-Type': 'application/json' },
383
+ body: JSON.stringify({
384
+ token,
385
+ client_id: process.env.CAS_CLIENT_ID,
386
+ client_secret: process.env.CAS_CLIENT_SECRET,
387
+ }),
388
+ });
389
+
390
+ if (!response.ok) {
391
+ return res.status(401).json({ error: 'Invalid token' });
392
+ }
393
+
394
+ // CAS responds with { valid, user: { id, username, email }, expires_at }.
395
+ // The SDK expects a bare CasUser, so return just the `user` object.
396
+ const { user } = await response.json();
397
+ res.json(user);
398
+ });
399
+ ```
400
+
401
+ ### Using with React Router
402
+
403
+ ```tsx
404
+ import { BrowserRouter, Routes, Route } from 'react-router-dom';
405
+ import { CasProvider, CasProtectedRoute } from '@cas-system/react-cas-client';
406
+
407
+ function App() {
408
+ return (
409
+ <BrowserRouter>
410
+ <CasProvider config={casConfig}>
411
+ <Routes>
412
+ <Route path="/" element={<Home />} />
413
+ <Route path="/auth/callback" element={<AuthCallback />} />
414
+ <Route
415
+ path="/dashboard/*"
416
+ element={
417
+ <CasProtectedRoute fallback={<Loading />}>
418
+ <DashboardRoutes />
419
+ </CasProtectedRoute>
420
+ }
421
+ />
422
+ </Routes>
423
+ </CasProvider>
424
+ </BrowserRouter>
425
+ );
426
+ }
427
+
428
+ // The callback page just renders normally — CasProvider auto-handles the token
429
+ function AuthCallback() {
430
+ return <p>Authenticating…</p>;
431
+ }
432
+ ```
433
+
434
+ ---
435
+
436
+ ## Session Storage
437
+
438
+ User data and tokens are stored in `sessionStorage` (not `localStorage`):
439
+
440
+ - `cas_user` — JSON-serialized `CasUser` object
441
+ - `cas_token` — Raw JWT token string
442
+
443
+ This means sessions are scoped to the browser tab and cleared when the tab is closed.
444
+
445
+ ---
446
+
447
+ ## License
448
+
449
+ MIT
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@cas-system/react-cas-client",
3
+ "version": "1.0.0",
4
+ "description": "React SDK for CAS (Central Authentication System) integration \u2014 provides hooks, components, and context for seamless SSO authentication.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "sideEffects": false,
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "peerDependencies": {
25
+ "react": ">=18.2"
26
+ },
27
+ "devDependencies": {
28
+ "@types/react": "^18.3.0",
29
+ "typescript": "^6.0.0"
30
+ },
31
+ "keywords": [
32
+ "react",
33
+ "cas",
34
+ "sso",
35
+ "authentication",
36
+ "central-authentication-system",
37
+ "one-system"
38
+ ],
39
+ "license": "MIT",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/InSol-2021/one-system.git",
43
+ "directory": "packages/react-cas-client"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }