@riao/authn-sso-google 1.0.0 → 2.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/CHANGELOG.md +1 -1
- package/LICENSE.md +20 -20
- package/README.md +254 -254
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
# auth-template - Changelog
|
|
1
|
+
# auth-template - Changelog
|
package/LICENSE.md
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
Copyright (c) 2022 auth-template and others
|
|
2
|
-
|
|
3
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
-
a copy of this software and associated documentation files (the
|
|
5
|
-
"Software"), to deal in the Software without restriction, including
|
|
6
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
-
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
-
the following conditions:
|
|
10
|
-
|
|
11
|
-
The above copyright notice and this permission notice shall be
|
|
12
|
-
included in all copies or substantial portions of the Software.
|
|
13
|
-
|
|
14
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
-
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
-
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
-
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
-
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
1
|
+
Copyright (c) 2022 auth-template and others
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,254 +1,254 @@
|
|
|
1
|
-
# @riao/authn-sso-google
|
|
2
|
-
|
|
3
|
-
Google OAuth2/OIDC authentication driver for riao-iam.
|
|
4
|
-
|
|
5
|
-
## Installation
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm install @riao/authn-sso-google @riao/iam @riao/dbal
|
|
9
|
-
npm install --save-dev @riao/cli
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
## Database Setup
|
|
13
|
-
|
|
14
|
-
Import SSO tables into your database:
|
|
15
|
-
|
|
16
|
-
```bash
|
|
17
|
-
npx riao migration:create import-sso-google-tables
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
`database/main/migrations/123456789-import-sso-tables.ts`:
|
|
21
|
-
|
|
22
|
-
```typescript
|
|
23
|
-
import { AuthenticationSSOMigrations } from '@riao/authn-sso/authentication-sso-migrations';
|
|
24
|
-
|
|
25
|
-
export default AuthenticationSSOMigrations;
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
Then run migrations:
|
|
29
|
-
|
|
30
|
-
```bash
|
|
31
|
-
npm run migration up
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
## Google OAuth Setup
|
|
35
|
-
|
|
36
|
-
### 1. Create a Google Cloud Project
|
|
37
|
-
|
|
38
|
-
1. Go to [Google Cloud Console](https://console.cloud.google.com)
|
|
39
|
-
2. Create a new project
|
|
40
|
-
3. Enable the Google+ API
|
|
41
|
-
|
|
42
|
-
### 2. Create OAuth 2.0 Credentials
|
|
43
|
-
|
|
44
|
-
1. Navigate to "Credentials" → "Create Credentials" → "OAuth client ID"
|
|
45
|
-
2. Choose "Web application"
|
|
46
|
-
3. Add authorized redirect URIs:
|
|
47
|
-
- `https://yourdomain.com/auth/google/callback`
|
|
48
|
-
- `http://localhost:3000/auth/google/callback` (for development)
|
|
49
|
-
4. Save the Client ID and Client Secret
|
|
50
|
-
|
|
51
|
-
### 3. Configuration
|
|
52
|
-
|
|
53
|
-
```typescript
|
|
54
|
-
import { GoogleAuthentication } from '@riao/authn-sso-google';
|
|
55
|
-
|
|
56
|
-
const googleAuth = new GoogleAuthentication({
|
|
57
|
-
db: database,
|
|
58
|
-
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
59
|
-
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
60
|
-
redirectUri: process.env.GOOGLE_REDIRECT_URI!,
|
|
61
|
-
});
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
### Environment Variables
|
|
65
|
-
|
|
66
|
-
```bash
|
|
67
|
-
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
|
68
|
-
GOOGLE_CLIENT_SECRET=your-client-secret
|
|
69
|
-
GOOGLE_REDIRECT_URI=https://yourdomain.com/auth/google/callback
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
### Custom Scopes
|
|
73
|
-
|
|
74
|
-
By default, the driver requests: `openid`, `profile`, `email`.
|
|
75
|
-
|
|
76
|
-
To customize scopes:
|
|
77
|
-
|
|
78
|
-
```typescript
|
|
79
|
-
const googleAuth = new GoogleAuthentication({
|
|
80
|
-
// ... other options
|
|
81
|
-
scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/calendar'],
|
|
82
|
-
});
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
## Usage
|
|
86
|
-
|
|
87
|
-
### Get Authorization URL
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
const state = await googleAuth.generateState(); // Generate and store state for CSRF protection
|
|
91
|
-
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
92
|
-
|
|
93
|
-
// Redirect user to authUrl
|
|
94
|
-
res.redirect(authUrl);
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
### Handle Callback
|
|
98
|
-
|
|
99
|
-
After user authorizes, Google redirects to your callback endpoint with `code` and `state`:
|
|
100
|
-
|
|
101
|
-
```typescript
|
|
102
|
-
const principal = await googleAuth.authenticate({
|
|
103
|
-
code: req.query.code as string,
|
|
104
|
-
state: req.query.state as string, // Validates CSRF protection
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
if (principal) {
|
|
108
|
-
// User authenticated successfully
|
|
109
|
-
// Create session, issue JWT, etc.
|
|
110
|
-
} else {
|
|
111
|
-
// Authentication failed
|
|
112
|
-
}
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
### Refresh Tokens
|
|
116
|
-
|
|
117
|
-
Automatically refresh access tokens using stored refresh tokens:
|
|
118
|
-
|
|
119
|
-
```typescript
|
|
120
|
-
// Retrieve stored token record for user
|
|
121
|
-
const tokenRecord = await ssoTokenRepo.findOneBy({ principal_id: userId });
|
|
122
|
-
|
|
123
|
-
// Refresh if expired
|
|
124
|
-
if (tokenRecord && tokenRecord.expires_at < new Date()) {
|
|
125
|
-
const newTokens = await googleAuth['exchangeRefreshToken'](
|
|
126
|
-
tokenRecord.refresh_token!
|
|
127
|
-
);
|
|
128
|
-
|
|
129
|
-
// Update token record with new values
|
|
130
|
-
tokenRecord.access_token = newTokens.access_token;
|
|
131
|
-
tokenRecord.expires_at = new Date(Date.now() + newTokens.expires_in * 1000);
|
|
132
|
-
await ssoTokenRepo.update(tokenRecord);
|
|
133
|
-
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
## Complete Example
|
|
137
|
-
|
|
138
|
-
```typescript
|
|
139
|
-
import express from 'express';
|
|
140
|
-
import session from 'express-session';
|
|
141
|
-
import { GoogleAuthentication } from '@riao/authn-sso-google';
|
|
142
|
-
|
|
143
|
-
const app = express();
|
|
144
|
-
|
|
145
|
-
// Setup session middleware
|
|
146
|
-
app.use(session({
|
|
147
|
-
secret: process.env.SESSION_SECRET!,
|
|
148
|
-
resave: false,
|
|
149
|
-
saveUninitialized: false,
|
|
150
|
-
}));
|
|
151
|
-
|
|
152
|
-
const googleAuth = new GoogleAuthentication({
|
|
153
|
-
db: database,
|
|
154
|
-
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
155
|
-
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
156
|
-
redirectUri: process.env.GOOGLE_REDIRECT_URI!,
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
// Redirect to Google login
|
|
160
|
-
// Uses generateState() to create and store state in database for CSRF protection
|
|
161
|
-
app.get('/auth/google', async (req, res) => {
|
|
162
|
-
try {
|
|
163
|
-
// generateState() creates a random state and stores it in the database
|
|
164
|
-
// The state will be validated in the callback handler
|
|
165
|
-
const state = await googleAuth.generateState();
|
|
166
|
-
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
167
|
-
res.redirect(authUrl);
|
|
168
|
-
} catch (error) {
|
|
169
|
-
res.redirect('/login?error=auth_error');
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
// Handle Google callback
|
|
174
|
-
app.get('/auth/google/callback', async (req, res) => {
|
|
175
|
-
const { code, state } = req.query as { code: string; state: string };
|
|
176
|
-
|
|
177
|
-
try {
|
|
178
|
-
// authenticate() validates the state against the database
|
|
179
|
-
// and handles the OAuth code exchange
|
|
180
|
-
const principal = await googleAuth.authenticate({ code, state });
|
|
181
|
-
|
|
182
|
-
if (principal) {
|
|
183
|
-
req.session.userId = principal.id;
|
|
184
|
-
res.redirect('/dashboard');
|
|
185
|
-
} else {
|
|
186
|
-
res.redirect('/login?error=auth_failed');
|
|
187
|
-
}
|
|
188
|
-
} catch (error) {
|
|
189
|
-
console.error('Authentication error:', error);
|
|
190
|
-
res.redirect('/login?error=auth_error');
|
|
191
|
-
}
|
|
192
|
-
});
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
## Troubleshooting
|
|
196
|
-
|
|
197
|
-
### "State validation failed or state not found"
|
|
198
|
-
|
|
199
|
-
This error occurs when the state parameter is not properly stored in the database before redirecting to Google.
|
|
200
|
-
|
|
201
|
-
**Solution:** Use `generateState()` to create and store the state:
|
|
202
|
-
|
|
203
|
-
```typescript
|
|
204
|
-
// ❌ WRONG - This won't work
|
|
205
|
-
app.get('/auth/google', (req, res) => {
|
|
206
|
-
const state = randomBytes(32).toString('hex'); // Not saved to database!
|
|
207
|
-
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
208
|
-
res.redirect(authUrl);
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
// ✅ CORRECT - State is saved to database
|
|
212
|
-
app.get('/auth/google', async (req, res) => {
|
|
213
|
-
const state = await googleAuth.generateState(); // Saves to database
|
|
214
|
-
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
215
|
-
res.redirect(authUrl);
|
|
216
|
-
});
|
|
217
|
-
```
|
|
218
|
-
|
|
219
|
-
The `generateState()` method creates a cryptographically random state and stores it in the database with an expiration time. The `authenticate()` method then validates this state during the callback to prevent CSRF attacks.
|
|
220
|
-
|
|
221
|
-
### "Database table not found"
|
|
222
|
-
|
|
223
|
-
Ensure you've run the SSO migrations to create the required tables:
|
|
224
|
-
|
|
225
|
-
```bash
|
|
226
|
-
npx riao migration:create import-sso-google-tables
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
Then add to your migration file:
|
|
230
|
-
|
|
231
|
-
```typescript
|
|
232
|
-
import { AuthenticationSSOMigrations } from '@riao/authn-sso/authentication-sso-migrations';
|
|
233
|
-
export default AuthenticationSSOMigrations;
|
|
234
|
-
```
|
|
235
|
-
|
|
236
|
-
Run migrations:
|
|
237
|
-
|
|
238
|
-
```bash
|
|
239
|
-
npm run migration up
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
## Contributing & Development
|
|
243
|
-
|
|
244
|
-
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
245
|
-
|
|
246
|
-
## Related Drivers
|
|
247
|
-
|
|
248
|
-
- [@riao/authn-sso](https://github.com/riao-project/authn-sso) - Base SSO driver
|
|
249
|
-
- [@riao/authn-sso-entra](https://github.com/riao-project/authn-sso-entra) - Microsoft Entra ID
|
|
250
|
-
- [@riao/authn-password](https://github.com/riao-project/authn-password) - Password authentication
|
|
251
|
-
|
|
252
|
-
## License
|
|
253
|
-
|
|
254
|
-
MIT
|
|
1
|
+
# @riao/authn-sso-google
|
|
2
|
+
|
|
3
|
+
Google OAuth2/OIDC authentication driver for riao-iam.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @riao/authn-sso-google @riao/iam @riao/dbal
|
|
9
|
+
npm install --save-dev @riao/cli
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Database Setup
|
|
13
|
+
|
|
14
|
+
Import SSO tables into your database:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npx riao migration:create import-sso-google-tables
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`database/main/migrations/123456789-import-sso-tables.ts`:
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { AuthenticationSSOMigrations } from '@riao/authn-sso/authentication-sso-migrations';
|
|
24
|
+
|
|
25
|
+
export default AuthenticationSSOMigrations;
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Then run migrations:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm run migration up
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Google OAuth Setup
|
|
35
|
+
|
|
36
|
+
### 1. Create a Google Cloud Project
|
|
37
|
+
|
|
38
|
+
1. Go to [Google Cloud Console](https://console.cloud.google.com)
|
|
39
|
+
2. Create a new project
|
|
40
|
+
3. Enable the Google+ API
|
|
41
|
+
|
|
42
|
+
### 2. Create OAuth 2.0 Credentials
|
|
43
|
+
|
|
44
|
+
1. Navigate to "Credentials" → "Create Credentials" → "OAuth client ID"
|
|
45
|
+
2. Choose "Web application"
|
|
46
|
+
3. Add authorized redirect URIs:
|
|
47
|
+
- `https://yourdomain.com/auth/google/callback`
|
|
48
|
+
- `http://localhost:3000/auth/google/callback` (for development)
|
|
49
|
+
4. Save the Client ID and Client Secret
|
|
50
|
+
|
|
51
|
+
### 3. Configuration
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { GoogleAuthentication } from '@riao/authn-sso-google';
|
|
55
|
+
|
|
56
|
+
const googleAuth = new GoogleAuthentication({
|
|
57
|
+
db: database,
|
|
58
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
59
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
60
|
+
redirectUri: process.env.GOOGLE_REDIRECT_URI!,
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Environment Variables
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
|
68
|
+
GOOGLE_CLIENT_SECRET=your-client-secret
|
|
69
|
+
GOOGLE_REDIRECT_URI=https://yourdomain.com/auth/google/callback
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Custom Scopes
|
|
73
|
+
|
|
74
|
+
By default, the driver requests: `openid`, `profile`, `email`.
|
|
75
|
+
|
|
76
|
+
To customize scopes:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
const googleAuth = new GoogleAuthentication({
|
|
80
|
+
// ... other options
|
|
81
|
+
scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/calendar'],
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Usage
|
|
86
|
+
|
|
87
|
+
### Get Authorization URL
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
const state = await googleAuth.generateState(); // Generate and store state for CSRF protection
|
|
91
|
+
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
92
|
+
|
|
93
|
+
// Redirect user to authUrl
|
|
94
|
+
res.redirect(authUrl);
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Handle Callback
|
|
98
|
+
|
|
99
|
+
After user authorizes, Google redirects to your callback endpoint with `code` and `state`:
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
const principal = await googleAuth.authenticate({
|
|
103
|
+
code: req.query.code as string,
|
|
104
|
+
state: req.query.state as string, // Validates CSRF protection
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
if (principal) {
|
|
108
|
+
// User authenticated successfully
|
|
109
|
+
// Create session, issue JWT, etc.
|
|
110
|
+
} else {
|
|
111
|
+
// Authentication failed
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Refresh Tokens
|
|
116
|
+
|
|
117
|
+
Automatically refresh access tokens using stored refresh tokens:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
// Retrieve stored token record for user
|
|
121
|
+
const tokenRecord = await ssoTokenRepo.findOneBy({ principal_id: userId });
|
|
122
|
+
|
|
123
|
+
// Refresh if expired
|
|
124
|
+
if (tokenRecord && tokenRecord.expires_at < new Date()) {
|
|
125
|
+
const newTokens = await googleAuth['exchangeRefreshToken'](
|
|
126
|
+
tokenRecord.refresh_token!
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
// Update token record with new values
|
|
130
|
+
tokenRecord.access_token = newTokens.access_token;
|
|
131
|
+
tokenRecord.expires_at = new Date(Date.now() + newTokens.expires_in * 1000);
|
|
132
|
+
await ssoTokenRepo.update(tokenRecord);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Complete Example
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
import express from 'express';
|
|
140
|
+
import session from 'express-session';
|
|
141
|
+
import { GoogleAuthentication } from '@riao/authn-sso-google';
|
|
142
|
+
|
|
143
|
+
const app = express();
|
|
144
|
+
|
|
145
|
+
// Setup session middleware
|
|
146
|
+
app.use(session({
|
|
147
|
+
secret: process.env.SESSION_SECRET!,
|
|
148
|
+
resave: false,
|
|
149
|
+
saveUninitialized: false,
|
|
150
|
+
}));
|
|
151
|
+
|
|
152
|
+
const googleAuth = new GoogleAuthentication({
|
|
153
|
+
db: database,
|
|
154
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
155
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
156
|
+
redirectUri: process.env.GOOGLE_REDIRECT_URI!,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Redirect to Google login
|
|
160
|
+
// Uses generateState() to create and store state in database for CSRF protection
|
|
161
|
+
app.get('/auth/google', async (req, res) => {
|
|
162
|
+
try {
|
|
163
|
+
// generateState() creates a random state and stores it in the database
|
|
164
|
+
// The state will be validated in the callback handler
|
|
165
|
+
const state = await googleAuth.generateState();
|
|
166
|
+
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
167
|
+
res.redirect(authUrl);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
res.redirect('/login?error=auth_error');
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Handle Google callback
|
|
174
|
+
app.get('/auth/google/callback', async (req, res) => {
|
|
175
|
+
const { code, state } = req.query as { code: string; state: string };
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
// authenticate() validates the state against the database
|
|
179
|
+
// and handles the OAuth code exchange
|
|
180
|
+
const principal = await googleAuth.authenticate({ code, state });
|
|
181
|
+
|
|
182
|
+
if (principal) {
|
|
183
|
+
req.session.userId = principal.id;
|
|
184
|
+
res.redirect('/dashboard');
|
|
185
|
+
} else {
|
|
186
|
+
res.redirect('/login?error=auth_failed');
|
|
187
|
+
}
|
|
188
|
+
} catch (error) {
|
|
189
|
+
console.error('Authentication error:', error);
|
|
190
|
+
res.redirect('/login?error=auth_error');
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Troubleshooting
|
|
196
|
+
|
|
197
|
+
### "State validation failed or state not found"
|
|
198
|
+
|
|
199
|
+
This error occurs when the state parameter is not properly stored in the database before redirecting to Google.
|
|
200
|
+
|
|
201
|
+
**Solution:** Use `generateState()` to create and store the state:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
// ❌ WRONG - This won't work
|
|
205
|
+
app.get('/auth/google', (req, res) => {
|
|
206
|
+
const state = randomBytes(32).toString('hex'); // Not saved to database!
|
|
207
|
+
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
208
|
+
res.redirect(authUrl);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// ✅ CORRECT - State is saved to database
|
|
212
|
+
app.get('/auth/google', async (req, res) => {
|
|
213
|
+
const state = await googleAuth.generateState(); // Saves to database
|
|
214
|
+
const authUrl = googleAuth.getAuthorizationUrl(state);
|
|
215
|
+
res.redirect(authUrl);
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
The `generateState()` method creates a cryptographically random state and stores it in the database with an expiration time. The `authenticate()` method then validates this state during the callback to prevent CSRF attacks.
|
|
220
|
+
|
|
221
|
+
### "Database table not found"
|
|
222
|
+
|
|
223
|
+
Ensure you've run the SSO migrations to create the required tables:
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
npx riao migration:create import-sso-google-tables
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Then add to your migration file:
|
|
230
|
+
|
|
231
|
+
```typescript
|
|
232
|
+
import { AuthenticationSSOMigrations } from '@riao/authn-sso/authentication-sso-migrations';
|
|
233
|
+
export default AuthenticationSSOMigrations;
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Run migrations:
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
npm run migration up
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## Contributing & Development
|
|
243
|
+
|
|
244
|
+
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
245
|
+
|
|
246
|
+
## Related Drivers
|
|
247
|
+
|
|
248
|
+
- [@riao/authn-sso](https://github.com/riao-project/authn-sso) - Base SSO driver
|
|
249
|
+
- [@riao/authn-sso-entra](https://github.com/riao-project/authn-sso-entra) - Microsoft Entra ID
|
|
250
|
+
- [@riao/authn-password](https://github.com/riao-project/authn-password) - Password authentication
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@riao/authn-sso-google",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Google OAuth2/OIDC SSO authentication driver for riao-iam",
|
|
5
5
|
"typescript-template": {
|
|
6
6
|
"base": "1.0.1",
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
},
|
|
10
10
|
"scripts": {},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@riao/authn-sso": "^
|
|
12
|
+
"@riao/authn-sso": "^2.0.0",
|
|
13
13
|
"@riao/dbal": "^3.8.0",
|
|
14
|
-
"@riao/iam": "^
|
|
14
|
+
"@riao/iam": "^4.0.0"
|
|
15
15
|
},
|
|
16
16
|
"repository": {
|
|
17
17
|
"type": "git",
|