witspry-auth-ng-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.
package/README.md ADDED
@@ -0,0 +1,280 @@
1
+ # witspry-auth-ng-client
2
+
3
+ A comprehensive Angular library for OAuth2 authentication with PKCE (Proof Key for Code Exchange) support. This library provides secure, configurable, and easy-to-use OAuth2 authentication for Angular applications.
4
+
5
+ ## Features
6
+
7
+ - ✅ **PKCE Support**: Implements OAuth2 PKCE flow with SHA-256 for enhanced security
8
+ - ✅ **Automatic Token Refresh**: Handles token refresh automatically with configurable thresholds
9
+ - ✅ **SSR Compatible**: Works with Angular Universal and server-side rendering
10
+ - ✅ **Configurable Storage**: Support for localStorage, sessionStorage, or custom storage
11
+ - ✅ **HTTP Interceptor**: Automatically adds Bearer tokens to HTTP requests
12
+ - ✅ **Route Guards**: Protect routes with authentication and role-based guards
13
+ - ✅ **TypeScript**: Full TypeScript support with comprehensive type definitions
14
+ - ✅ **Standalone Components**: Support for Angular 14+ standalone components
15
+ - ✅ **Customizable**: Highly configurable to work with different OAuth2 providers
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install witspry-auth-ng-client
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ### 1. Configure OAuth2 in your app
26
+
27
+ ```typescript
28
+ // app.config.ts
29
+ import { ApplicationConfig } from '@angular/core';
30
+ import { provideRouter } from '@angular/router';
31
+ import { provideOAuth2 } from 'witspry-auth-ng-client';
32
+
33
+ export const appConfig: ApplicationConfig = {
34
+ providers: [
35
+ provideRouter(routes),
36
+ provideOAuth2({
37
+ clientId: 'your-client-id',
38
+ redirectUri: 'http://localhost:4200/auth/callback',
39
+ authorizationEndpoint: 'https://your-auth-server.com/auth/authorize',
40
+ tokenEndpoint: 'https://your-auth-server.com/auth/oauth/token',
41
+ revokeEndpoint: 'https://your-auth-server.com/auth/oauth/revoke',
42
+ userInfoEndpoint: 'https://your-auth-server.com/userinfo',
43
+ scope: 'openid profile email',
44
+ audience: 'https://your-api.com'
45
+ })
46
+ ]
47
+ };
48
+ ```
49
+
50
+ ### 2. Add callback route
51
+
52
+ ```typescript
53
+ // app.routes.ts
54
+ import { Routes } from '@angular/router';
55
+ import { OAuth2CallbackComponent } from 'witspry-auth-ng-client';
56
+
57
+ export const routes: Routes = [
58
+ {
59
+ path: 'auth/callback',
60
+ component: OAuth2CallbackComponent
61
+ },
62
+ // ... other routes
63
+ ];
64
+ ```
65
+
66
+ ### 3. Use in your components
67
+
68
+ ```typescript
69
+ // login.component.ts
70
+ import { Component } from '@angular/core';
71
+ import { OAuth2Service } from 'witspry-auth-ng-client';
72
+
73
+ @Component({
74
+ selector: 'app-login',
75
+ template: `
76
+ <button (click)="login()" [disabled]="!oauth2Service.isAuthenticationAvailable()">
77
+ Login with OAuth2
78
+ </button>
79
+ `
80
+ })
81
+ export class LoginComponent {
82
+ constructor(public oauth2Service: OAuth2Service) {}
83
+
84
+ login() {
85
+ this.oauth2Service.startAuthorization();
86
+ }
87
+ }
88
+ ```
89
+
90
+ ### 4. Protect routes with guards
91
+
92
+ ```typescript
93
+ // app.routes.ts
94
+ import { Routes } from '@angular/router';
95
+ import { oauth2AuthGuard } from 'witspry-auth-ng-client';
96
+
97
+ export const routes: Routes = [
98
+ {
99
+ path: 'protected',
100
+ component: ProtectedComponent,
101
+ canActivate: [oauth2AuthGuard]
102
+ }
103
+ ];
104
+ ```
105
+
106
+ ## Configuration Options
107
+
108
+ ```typescript
109
+ interface OAuth2Config {
110
+ clientId: string; // OAuth2 Client ID
111
+ redirectUri: string; // Redirect URI for callback
112
+ authorizationEndpoint: string; // Authorization endpoint URL
113
+ tokenEndpoint: string; // Token endpoint URL
114
+ revokeEndpoint?: string; // Token revocation endpoint (optional)
115
+ userInfoEndpoint?: string; // OIDC UserInfo endpoint (optional)
116
+ audience?: string; // OAuth2 audience parameter (optional)
117
+ scope: string; // OAuth2 scope parameter
118
+ responseType?: 'code'; // Response type (default: 'code')
119
+ codeChallengeMethod?: 'S256'; // PKCE method (default: 'S256')
120
+ storage?: 'localStorage' | 'sessionStorage' | 'custom'; // Storage strategy
121
+ customStorage?: OAuth2Storage; // Custom storage implementation
122
+ autoRefresh?: boolean; // Enable auto token refresh (default: true)
123
+ refreshThreshold?: number; // Seconds before expiry to refresh (default: 300)
124
+ logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug'; // Logging level
125
+ nonce?: string; // Custom nonce (optional)
126
+ }
127
+ ```
128
+
129
+ ## Advanced Usage
130
+
131
+ ### Custom Storage
132
+
133
+ ```typescript
134
+ import { OAuth2Storage } from 'witspry-auth-ng-client';
135
+
136
+ class CustomStorage implements OAuth2Storage {
137
+ getItem(key: string): string | null {
138
+ // Your custom storage logic
139
+ return null;
140
+ }
141
+
142
+ setItem(key: string, value: string): void {
143
+ // Your custom storage logic
144
+ }
145
+
146
+ removeItem(key: string): void {
147
+ // Your custom storage logic
148
+ }
149
+ }
150
+
151
+ // Use in configuration
152
+ provideOAuth2({
153
+ // ... other config
154
+ storage: 'custom',
155
+ customStorage: new CustomStorage()
156
+ })
157
+ ```
158
+
159
+ ### Custom Redirect Route
160
+
161
+ ```typescript
162
+ import { OAuth2Config } from 'witspry-auth-ng-client';
163
+
164
+ const oauth2Config: OAuth2Config = {
165
+ clientId: 'your-client-id',
166
+ redirectUri: 'http://localhost:4200/oauth2/callback',
167
+ authorizationEndpoint: 'https://auth.example.com/oauth2/authorize',
168
+ tokenEndpoint: 'https://auth.example.com/oauth2/token',
169
+ scope: 'openid profile email',
170
+ redirectRoute: '/dashboard' // Custom redirect route
171
+ };
172
+ ```
173
+
174
+ ### Role-based Guards
175
+
176
+ ```typescript
177
+ import { oauth2RoleGuard } from 'witspry-auth-ng-client';
178
+
179
+ const routes: Routes = [
180
+ {
181
+ path: 'admin',
182
+ component: AdminComponent,
183
+ canActivate: [oauth2RoleGuard({
184
+ roles: ['admin', 'super-admin'],
185
+ requireAll: false // User needs ANY of the roles
186
+ })]
187
+ }
188
+ ];
189
+ ```
190
+
191
+ ### Manual HTTP Interceptor Setup
192
+
193
+ ```typescript
194
+ // If you want to configure the HTTP interceptor manually
195
+ import { provideOAuth2WithoutInterceptor, oauth2InterceptorFn } from 'witspry-auth-ng-client';
196
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
197
+
198
+ export const appConfig: ApplicationConfig = {
199
+ providers: [
200
+ provideOAuth2WithoutInterceptor(config),
201
+ provideHttpClient(
202
+ withInterceptors([oauth2InterceptorFn])
203
+ )
204
+ ]
205
+ };
206
+ ```
207
+
208
+ ### Using with NgModule (Legacy)
209
+
210
+ ```typescript
211
+ // app.module.ts
212
+ import { NgOAuth2PkceModule } from 'witspry-auth-ng-client';
213
+
214
+ @NgModule({
215
+ imports: [
216
+ NgOAuth2PkceModule.forRoot({
217
+ clientId: 'your-client-id',
218
+ // ... other config
219
+ })
220
+ ]
221
+ })
222
+ export class AppModule {}
223
+ ```
224
+
225
+ ## API Reference
226
+
227
+ ### OAuth2Service
228
+
229
+ #### Methods
230
+
231
+ - `startAuthorization(): Promise<void>` - Start OAuth2 authorization flow
232
+ - `handleCallback(): Promise<void>` - Handle OAuth2 callback
233
+ - `getAccessToken(): string | null` - Get current valid access token
234
+ - `getRefreshToken(): string | null` - Get current refresh token
235
+ - `isAuthenticated(): boolean` - Check if user is authenticated
236
+ - `getUserInfo(): Promise<UserInfoResponse>` - Get user information
237
+ - `refreshAccessToken(): Promise<string>` - Manually refresh access token
238
+ - `logout(): Promise<void>` - Logout user and clear tokens
239
+
240
+ #### Properties
241
+
242
+ - `authState$: Observable<AuthState>` - Observable of authentication state
243
+ - `authState: Signal<AuthState>` - Signal of authentication state
244
+
245
+ ### Guards
246
+
247
+ - `oauth2AuthGuard` - Protect routes requiring authentication
248
+ - `oauth2UnauthGuard` - Protect routes for unauthenticated users only
249
+ - `oauth2RoleGuard(config)` - Protect routes based on user roles/permissions
250
+
251
+ ### Components
252
+
253
+ - `OAuth2CallbackComponent` - Handle OAuth2 callback with UI feedback
254
+
255
+ ## Browser Support
256
+
257
+ This library supports all modern browsers that support:
258
+ - Web Crypto API (for PKCE)
259
+ - ES2017+ features
260
+ - Angular 19+
261
+
262
+ ## Contributing
263
+
264
+ Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
265
+
266
+ ## License
267
+
268
+ MIT License - see LICENSE file for details.
269
+
270
+ ## Changelog
271
+
272
+ ### 1.0.0
273
+ - Initial release
274
+ - OAuth2 PKCE implementation
275
+ - Automatic token refresh
276
+ - SSR support
277
+ - Configurable storage
278
+ - HTTP interceptor
279
+ - Route guards
280
+ - TypeScript support