dserver-token-generator-plugin-oauth2 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,36 @@
1
+ """
2
+ dserver-token-generator-plugin-oauth2
3
+
4
+ A generic OAuth 2.0 token generator plugin for dserver that integrates with
5
+ any OAuth 2.0 / OpenID Connect compliant Identity Provider.
6
+
7
+ Supported providers include:
8
+ - ORCID
9
+ - GitHub
10
+ - Google
11
+ - Azure AD / Microsoft Entra ID
12
+ - Keycloak
13
+ - Any OAuth 2.0 / OIDC compliant provider
14
+
15
+ This plugin provides:
16
+ - OAuth 2.0 Authorization Code flow
17
+ - OpenID Connect support (where available)
18
+ - JWT token generation after successful authentication
19
+ - User auto-provisioning from OAuth2/OIDC claims
20
+ """
21
+
22
+ try:
23
+ from importlib.metadata import version, PackageNotFoundError
24
+ except ModuleNotFoundError:
25
+ from importlib_metadata import version, PackageNotFoundError
26
+
27
+ try:
28
+ __version__ = version(__name__)
29
+ except PackageNotFoundError:
30
+ # package is not installed
31
+ pass
32
+
33
+ from .plugin import OAuth2TokenGeneratorPlugin
34
+ from .blueprint import oauth2_bp
35
+
36
+ __all__ = ["OAuth2TokenGeneratorPlugin", "oauth2_bp", "__version__"]
@@ -0,0 +1,493 @@
1
+ """
2
+ Flask blueprint for OAuth2 authentication.
3
+
4
+ This blueprint provides the following endpoints:
5
+ - GET /auth/oauth2/login - Initiate OAuth2 authorization flow
6
+ - GET /auth/oauth2/callback - OAuth2 callback (receives authorization code)
7
+ - GET/POST /auth/oauth2/logout - Clear session and logout
8
+ - GET /auth/oauth2/token - Get current user's JWT token
9
+ - POST /auth/oauth2/refresh - Refresh a JWT token, at most until
10
+ JWT_MAX_SESSION_HOURS after the original login
11
+ - POST /auth/oauth2/verify - Verify a JWT token
12
+ """
13
+
14
+ import logging
15
+ import secrets
16
+ from typing import Optional
17
+ from urllib.parse import urlparse
18
+
19
+ import httpx
20
+ from authlib.integrations.requests_client import OAuth2Session
21
+ from flask import (
22
+ jsonify,
23
+ make_response,
24
+ redirect,
25
+ request,
26
+ session,
27
+ url_for,
28
+ )
29
+ from flask_smorest import Blueprint
30
+
31
+ from .config import PluginConfig
32
+ from .jwt_utils import JwtTokenGenerator
33
+ from .user_provisioning import UserProvisioner
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ # Create the blueprint using flask_smorest Blueprint (required by dservercore)
38
+ oauth2_bp = Blueprint(
39
+ "oauth2_auth",
40
+ __name__,
41
+ url_prefix="/auth/oauth2",
42
+ description="OAuth2 authentication endpoints"
43
+ )
44
+
45
+ # Plugin configuration (initialized on first request)
46
+ _config: PluginConfig = None
47
+ _jwt_generator: JwtTokenGenerator = None
48
+ _user_provisioner: UserProvisioner = None
49
+
50
+
51
+ def get_config() -> PluginConfig:
52
+ """Get or initialize plugin configuration."""
53
+ global _config
54
+ if _config is None:
55
+ _config = PluginConfig.from_env()
56
+ return _config
57
+
58
+
59
+ def get_jwt_generator() -> JwtTokenGenerator:
60
+ """Get or initialize JWT token generator."""
61
+ global _jwt_generator
62
+ if _jwt_generator is None:
63
+ config = get_config()
64
+ _jwt_generator = JwtTokenGenerator(config.jwt)
65
+ return _jwt_generator
66
+
67
+
68
+ def get_user_provisioner() -> UserProvisioner:
69
+ """Get or initialize user provisioner."""
70
+ global _user_provisioner
71
+ if _user_provisioner is None:
72
+ config = get_config()
73
+ _user_provisioner = UserProvisioner(
74
+ auto_provision=config.auto_provision_users,
75
+ default_permissions=config.default_user_permissions,
76
+ )
77
+ return _user_provisioner
78
+
79
+
80
+ def create_oauth2_session() -> OAuth2Session:
81
+ """Create an OAuth2 session for the configured provider."""
82
+ config = get_config()
83
+ return OAuth2Session(
84
+ client_id=config.oauth2.client_id,
85
+ client_secret=config.oauth2.client_secret,
86
+ redirect_uri=config.oauth2.redirect_uri,
87
+ scope=config.oauth2.scope,
88
+ )
89
+
90
+
91
+ def extract_user_info(token_response: dict, userinfo: Optional[dict] = None) -> dict:
92
+ """
93
+ Extract user information from OAuth2 token response and/or userinfo.
94
+
95
+ Some providers (like ORCID) return user info directly in the token response,
96
+ while others require a separate userinfo endpoint call.
97
+
98
+ Args:
99
+ token_response: The OAuth2 token response
100
+ userinfo: Optional userinfo response from userinfo endpoint
101
+
102
+ Returns:
103
+ Dictionary with extracted user information
104
+ """
105
+ config = get_config()
106
+
107
+ # Combine token response and userinfo
108
+ data = {**token_response}
109
+ if userinfo:
110
+ data.update(userinfo)
111
+
112
+ # Map attributes according to configuration
113
+ user_data = {}
114
+ for provider_field, internal_field in config.oauth2.attribute_map.items():
115
+ if provider_field in data:
116
+ user_data[internal_field] = data[provider_field]
117
+
118
+ # Store the raw provider user ID
119
+ if "sub" in data:
120
+ user_data["provider_user_id"] = data["sub"]
121
+ elif "id" in data:
122
+ user_data["provider_user_id"] = str(data["id"])
123
+ elif "orcid" in data:
124
+ user_data["provider_user_id"] = data["orcid"]
125
+
126
+ return user_data
127
+
128
+
129
+ def is_safe_return_url(url: str, config: PluginConfig) -> bool:
130
+ """Return True if a post-login redirect target is safe to use.
131
+
132
+ Only relative paths and absolute URLs on explicitly trusted origins
133
+ (frontend URL, configured redirect targets, base URL) are allowed.
134
+ Anything else enables an open redirect that leaks the JWT to an
135
+ attacker-controlled site.
136
+ """
137
+ if not url:
138
+ return False
139
+
140
+ parsed = urlparse(url)
141
+ if not parsed.scheme and not parsed.netloc:
142
+ # Relative path. Exclude protocol-relative ("//host") and
143
+ # backslash variants some browsers normalize to "//".
144
+ return url.startswith("/") and not url.startswith("//") \
145
+ and not url.startswith("/\\")
146
+
147
+ trusted_origins = set()
148
+ for candidate in (config.frontend_url, config.login_success_redirect,
149
+ config.login_error_redirect, config.base_url):
150
+ if not candidate:
151
+ continue
152
+ parsed_candidate = urlparse(candidate)
153
+ if parsed_candidate.scheme and parsed_candidate.netloc:
154
+ trusted_origins.add(
155
+ (parsed_candidate.scheme, parsed_candidate.netloc))
156
+
157
+ return (parsed.scheme, parsed.netloc) in trusted_origins
158
+
159
+
160
+ def get_username_from_user_data(user_data: dict) -> Optional[str]:
161
+ """
162
+ Determine the username from extracted user data.
163
+
164
+ Args:
165
+ user_data: Mapped user attributes
166
+
167
+ Returns:
168
+ Username string or None
169
+ """
170
+ config = get_config()
171
+ username_field = config.oauth2.username_field
172
+
173
+ if username_field in user_data:
174
+ return str(user_data[username_field])
175
+
176
+ # Fallbacks
177
+ for field in ["user_id", "email", "username", "provider_user_id"]:
178
+ if field in user_data:
179
+ return str(user_data[field])
180
+
181
+ return None
182
+
183
+
184
+ @oauth2_bp.route("/login")
185
+ def login():
186
+ """
187
+ Initiate OAuth2 authorization flow.
188
+
189
+ This endpoint redirects the user to the OAuth2 provider for authentication.
190
+
191
+ Query Parameters:
192
+ next: URL to redirect to after successful login (optional)
193
+ """
194
+ try:
195
+ config = get_config()
196
+
197
+ if not config.oauth2.authorization_url:
198
+ return jsonify({
199
+ "error": "OAuth2 not configured",
200
+ "message": "OAUTH2_AUTHORIZATION_URL is not set"
201
+ }), 500
202
+
203
+ # Generate state for CSRF protection
204
+ state = secrets.token_urlsafe(32)
205
+ session["oauth2_state"] = state
206
+ session.modified = True # Ensure session is saved
207
+
208
+ # Store the return URL; reject untrusted targets to prevent an
209
+ # open redirect that would hand the JWT to an attacker's site.
210
+ next_url = request.args.get("next")
211
+ if next_url and not is_safe_return_url(next_url, config):
212
+ logger.warning(
213
+ f"Rejected untrusted post-login redirect target: {next_url}")
214
+ next_url = None
215
+ session["auth_return_url"] = next_url or config.login_success_redirect
216
+
217
+ # Build authorization URL
218
+ oauth = create_oauth2_session()
219
+ authorization_url, _ = oauth.create_authorization_url(
220
+ config.oauth2.authorization_url,
221
+ state=state,
222
+ )
223
+
224
+ logger.info(f"Initiating OAuth2 login, redirecting to provider")
225
+ logger.debug(f"Authorization URL: {authorization_url}")
226
+ return redirect(authorization_url)
227
+
228
+ except Exception as e:
229
+ logger.error(f"Error initiating OAuth2 login: {e}")
230
+ return jsonify({"error": "Failed to initiate authentication"}), 500
231
+
232
+
233
+ @oauth2_bp.route("/callback")
234
+ def callback():
235
+ """
236
+ OAuth2 callback endpoint.
237
+
238
+ This endpoint receives the authorization code from the OAuth2 provider
239
+ and exchanges it for an access token.
240
+ """
241
+ try:
242
+ config = get_config()
243
+
244
+ # Verify state for CSRF protection
245
+ state = request.args.get("state")
246
+ stored_state = session.pop("oauth2_state", None)
247
+
248
+ if not state or not stored_state or \
249
+ not secrets.compare_digest(state, stored_state):
250
+ # Do not log state values; they are security tokens.
251
+ logger.warning("OAuth2 state mismatch or missing state")
252
+ return redirect(config.login_error_redirect)
253
+
254
+ # Check for errors from provider
255
+ error = request.args.get("error")
256
+ if error:
257
+ error_description = request.args.get("error_description", "Unknown error")
258
+ logger.error(f"OAuth2 error: {error} - {error_description}")
259
+ return redirect(config.login_error_redirect)
260
+
261
+ # Get authorization code
262
+ code = request.args.get("code")
263
+ if not code:
264
+ logger.error("No authorization code received")
265
+ return redirect(config.login_error_redirect)
266
+
267
+ # Exchange code for token
268
+ oauth = create_oauth2_session()
269
+ token_response = oauth.fetch_token(
270
+ config.oauth2.token_url,
271
+ authorization_response=request.url,
272
+ code=code,
273
+ )
274
+
275
+ logger.debug(f"Token response: {token_response}")
276
+
277
+ # Fetch userinfo if endpoint is configured
278
+ userinfo = None
279
+ if config.oauth2.userinfo_url:
280
+ try:
281
+ access_token = token_response.get("access_token")
282
+ with httpx.Client() as client:
283
+ resp = client.get(
284
+ config.oauth2.userinfo_url,
285
+ headers={"Authorization": f"Bearer {access_token}"}
286
+ )
287
+ resp.raise_for_status()
288
+ userinfo = resp.json()
289
+ logger.debug(f"Userinfo response: {userinfo}")
290
+ except Exception as e:
291
+ logger.warning(f"Failed to fetch userinfo: {e}")
292
+
293
+ # Extract user information
294
+ user_data = extract_user_info(token_response, userinfo)
295
+ logger.debug(f"Extracted user data: {user_data}")
296
+
297
+ # Get username
298
+ username = get_username_from_user_data(user_data)
299
+ if not username:
300
+ logger.error("Could not determine username from OAuth2 response")
301
+ return redirect(config.login_error_redirect)
302
+
303
+ # Provision user
304
+ provisioner = get_user_provisioner()
305
+ user_info = provisioner.provision_user(
306
+ username=username,
307
+ email=user_data.get("email"),
308
+ display_name=user_data.get("display_name"),
309
+ given_name=user_data.get("given_name"),
310
+ surname=user_data.get("surname"),
311
+ provider=config.oauth2.name,
312
+ provider_user_id=user_data.get("provider_user_id"),
313
+ )
314
+
315
+ # Generate JWT token
316
+ jwt_gen = get_jwt_generator()
317
+ token = jwt_gen.generate_token(
318
+ username=user_info["username"],
319
+ email=user_info.get("email"),
320
+ display_name=user_info.get("display_name"),
321
+ permissions=user_info.get("permissions"),
322
+ additional_claims={
323
+ "provider": config.oauth2.name,
324
+ "provider_user_id": user_data.get("provider_user_id"),
325
+ },
326
+ )
327
+
328
+ # Store session info
329
+ session["username"] = username
330
+ session["jwt_token"] = token
331
+ session["provider"] = config.oauth2.name
332
+
333
+ # Redirect to frontend
334
+ return_url = session.pop("auth_return_url", config.login_success_redirect)
335
+ if not is_safe_return_url(return_url, config):
336
+ return_url = config.login_success_redirect
337
+
338
+ if config.deliver_token_in_fragment:
339
+ # Deliver the token in the URL fragment: fragments are never
340
+ # sent to servers, so the token stays out of server logs,
341
+ # proxies and Referer headers (unlike a query parameter). This
342
+ # supports webapps served from a different origin than this
343
+ # endpoint.
344
+ response = make_response(redirect(f"{return_url}#token={token}"))
345
+ else:
346
+ # Session-only delivery: the token never appears in the URL at
347
+ # all (not even in browser history). The webapp obtains it via
348
+ # GET /auth/token, authenticated by the session cookie set
349
+ # above. This requires the webapp to be served from the same
350
+ # origin as this endpoint (e.g. behind a shared reverse proxy)
351
+ # or CORS with credentials.
352
+ response = make_response(redirect(return_url))
353
+
354
+ logger.info(f"User {username} authenticated successfully via {config.oauth2.name}")
355
+ return response
356
+
357
+ except Exception as e:
358
+ logger.exception(f"Error processing OAuth2 callback: {e}")
359
+ return redirect(get_config().login_error_redirect)
360
+
361
+
362
+ @oauth2_bp.route("/logout", methods=["GET", "POST"])
363
+ def logout():
364
+ """
365
+ Logout and clear the server-side session.
366
+
367
+ Browser navigations are redirected back to the frontend; clients that
368
+ ask for JSON (e.g. the webapp terminating the session via XHR after a
369
+ local logout) receive a JSON response instead of a redirect.
370
+ """
371
+ config = get_config()
372
+
373
+ # Clear session
374
+ session.clear()
375
+
376
+ accepts = request.accept_mimetypes
377
+ if accepts.accept_json and not accepts.accept_html:
378
+ response = make_response(jsonify({"success": True}))
379
+ else:
380
+ response = make_response(redirect(config.frontend_url))
381
+
382
+ # Remove the token cookie set by older plugin versions.
383
+ response.delete_cookie("dserver_token")
384
+
385
+ logger.info("User logged out")
386
+ return response
387
+
388
+
389
+ @oauth2_bp.route("/token", methods=["GET"])
390
+ def get_token():
391
+ """
392
+ Get the current user's JWT token.
393
+
394
+ Returns:
395
+ JSON with token or error
396
+ """
397
+ token = session.get("jwt_token")
398
+
399
+ if not token:
400
+ return jsonify({
401
+ "error": "Not authenticated",
402
+ "login_url": url_for("oauth2_auth.login", _external=True),
403
+ }), 401
404
+
405
+ username = session.get("username")
406
+ provider = session.get("provider")
407
+
408
+ return jsonify({
409
+ "token": token,
410
+ "username": username,
411
+ "provider": provider,
412
+ "token_type": "Bearer",
413
+ })
414
+
415
+
416
+ @oauth2_bp.route("/refresh", methods=["POST"])
417
+ def refresh_token():
418
+ """
419
+ Refresh an existing JWT token.
420
+
421
+ Request body:
422
+ {
423
+ "token": "existing_jwt_token"
424
+ }
425
+
426
+ Returns:
427
+ JSON with new token or error
428
+ """
429
+ data = request.get_json()
430
+
431
+ if not data or "token" not in data:
432
+ return jsonify({"error": "Missing token"}), 400
433
+
434
+ jwt_gen = get_jwt_generator()
435
+ new_token = jwt_gen.refresh_token(data["token"])
436
+
437
+ if not new_token:
438
+ return jsonify({"error": "Invalid or expired token"}), 401
439
+
440
+ return jsonify({
441
+ "token": new_token,
442
+ "token_type": "Bearer",
443
+ })
444
+
445
+
446
+ @oauth2_bp.route("/verify", methods=["POST"])
447
+ def verify_token():
448
+ """
449
+ Verify a JWT token and return its claims.
450
+
451
+ Request body:
452
+ {
453
+ "token": "jwt_token_to_verify"
454
+ }
455
+
456
+ Returns:
457
+ JSON with token claims or error
458
+ """
459
+ data = request.get_json()
460
+
461
+ if not data or "token" not in data:
462
+ return jsonify({"error": "Missing token"}), 400
463
+
464
+ jwt_gen = get_jwt_generator()
465
+ claims = jwt_gen.verify_token(data["token"])
466
+
467
+ if not claims:
468
+ return jsonify({"error": "Invalid or expired token"}), 401
469
+
470
+ return jsonify({
471
+ "valid": True,
472
+ "claims": claims,
473
+ })
474
+
475
+
476
+ @oauth2_bp.route("/info")
477
+ def auth_info():
478
+ """
479
+ Return information about the configured OAuth2 provider.
480
+
481
+ This endpoint can be used by the frontend to display login options.
482
+ """
483
+ config = get_config()
484
+
485
+ return jsonify({
486
+ "provider": config.oauth2.name,
487
+ "login_url": url_for("oauth2_auth.login", _external=True),
488
+ "configured": bool(config.oauth2.authorization_url and config.oauth2.client_id),
489
+ })
490
+
491
+
492
+ # Device authorization flow routes are registered on this blueprint.
493
+ from . import device_flow # noqa: E402,F401