Skip to main content

DataONE Auth Library for python services

The dataone-auth module provides a framework-agnostic OpenID Connect (OIDC) authentication adapter for Python applications. Using joserfc and Authlib, its core purpose is to handle JSON Web Token (JWT) validation so that DataONE Python applications can seamlessly integrate OIDC authentication, regardless of what framework that application uses. Currently, dataone-auth supports both Flask and FastAPI. To integrate dataone-auth into an existing app, the application only needs to create an auth client (create_client), use the login, authorize, refresh methods on the corresponding endpoints, and utilize the require_scope helper either as a decorator or Depends function to protect secure endpoints. For more detail on usage, see the examples below.

DataONE creates open source, community projects. We welcome contributions in many forms, including code, graphics, documentation, bug reports, testing, etc. Use the DataONE discussions to discuss these contributions with us.

Documentation

Documentation is a work in progress, and can be found in docs.

Development build

This is a python package, and built using the uv build tool, among others.

To install locally, create a virtual environment for python. Install uv, and then sync the package dependencies:

  • uv sync.

Then import it in your code:

import dataone.auth

To run tests, navigate to the root directory and run pytest:

  • uv run pytest

To run the code formatter and linter, use Ruff:

  • uv run ruff check .

Usage Examples

Flask

Below is a minimal example for a Flask application. For the Flask implementation, applying ProxyFix is recommended to ensure correct redirect URIs when the app is running behind a reverse proxy or load balancer. Following standard Flask extension patterns, the auth_client must be explicitly bound to the application using init_app(). Once initialized, protect any endpoint by stacking the @auth_client.require_scope(...) decorator below the route definition. This automatically intercepts the Bearer token, validates the OIDC claims against the provider's JWKS, and injects the resulting claims dictionary into the view function. Note that routes can also use @auth_client.require_token(...) if checking scopes is not necessary. Optionally, HTTP methods can be passed to either decorator to specify auth requirements based on method if necessary.

import json
import os
from flask import Flask, jsonify, request, url_for
from werkzeug.middleware.proxy_fix import ProxyFix
from dataone.auth import AuthFactory, load_client_secrets

# --- Constants & Logging ---
ACCESS_MODE_AUTHENTICATED = "authenticated"
scopes = ["ogdc:admin"]

# --- App Initialization ---
app = Flask(__name__)
app.config.update({"SECRET_KEY": os.getenv("FLASK_SECRET_KEY", os.urandom(32).hex())})

if not isinstance(app.wsgi_app, ProxyFix):
    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

# --- Auth Setup ---
secrets = load_client_secrets()
auth_client = AuthFactory.create_client("flask", secrets, scopes)
auth_client.init_app(app)
app.extensions['dataone_auth'] = auth_client

# --- Routes ---
@app.route("/login")
def login():
    return auth_client.login(redirect_uri=url_for("authorize", _external=True))

@app.route("/authorize")
def authorize():
    return auth_client.authorize()

@app.route("/refresh", methods=["POST"])
def refresh_token():
    return auth_client.refresh(request_json=request.get_json(silent=True))

@app.route("/profile", methods=["GET"])
@auth_client.require_scope("ogdc:admin")
def profile(claims):
    """Protected resource endpoint requiring 'ogdc:admin' scope."""
    return jsonify({
        "message": f"Authorization succeeded, {claims.get('name', 'User')}",
        "claims": claims  # The claims object is already a dictionary!
    }), 200

# --- Execution ---
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int("4000"), debug=True)

FastAPI

Below is a minimal example for a FastAPI application. Unlike Flask, FastAPI doesn't require an init_app step; the auth_client is ready to use immediately upon creation. Note that SessionMiddleware must be added to the app to handle the OIDC state and nonce during the browser-based login and authorization flow. For the API endpoints, the heavy lifting happens within the Depends(auth_client.require_scope(...)) dependency, which automatically intercepts the Bearer token, validates the OIDC claims against the provider's JWKS, and injects the ready-to-use claims dictionary into the route handler. Note that routes can also use Depends(auth_client.require_token(...)) if checking scopes is not necessary. Optionally, HTTP methods can be passed to either Depends to specify auth requirements based on method if necessary.

import os
from fastapi import Depends, FastAPI, Request
from fastapi.security import HTTPBearer
from starlette.middleware.sessions import SessionMiddleware
from dataone.auth import AuthFactory, load_client_secrets

# --- Constants & Logging ---
ACCESS_MODE_AUTHENTICATED = "authenticated"
scopes = ["ogdc:admin"]

# --- App Initialization ---
app = FastAPI(title="DataONE OIDC API")
app.add_middleware(
    SessionMiddleware, 
    secret_key=os.getenv("SECRET_KEY", os.urandom(32).hex())
)

# --- Auth Setup ---
secrets = load_client_secrets()
auth_client = AuthFactory.create_client("fastapi", secrets, scopes)

security = HTTPBearer()
# --- Routes ---
@app.get("/login")
async def login(request: Request):
    return await auth_client.login(request, redirect_uri=str(request.url_for("authorize")))

@app.get("/authorize")
async def authorize(request: Request):
    return await auth_client.authorize(request)

@app.post("/refresh")
async def refresh(request: Request):
    return await auth_client.refresh(await request.json())

@app.get("/profile")
async def profile(claims: dict = Depends(auth_client.require_scope("ogdc:admin"))):
    """Protected resource endpoint."""
    return {
        "message": f"Authorization succeeded, {claims.get('name', 'User')}",
        "claims": claims
    }

# --- Execution ---
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=4000, proxy_headers=True, forwarded_allow_ips="*")

License

Copyright [2024] [Regents of the University of California]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Acknowledgements

Work on this package was supported by:

  • DataONE Network
  • Arctic Data Center: NSF-PLR grant #2042102 to M. B. Jones, A. Budden, M. Schildhauer, and J. Dozier

Additional support was provided for collaboration by the National Center for Ecological Analysis and Synthesis, a Center funded by the University of California, Santa Barbara, and the State of California.

DataONE_footer

nceas_footer

Metadata

Release files for dataone-auth 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dataone-auth 0.1.1
File Size Uploaded Provenance Actions
dataone_auth-0.1.1.tar.gz 90.5 kB With provenance Details for dataone_auth-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dataone-auth 0.1.1
File Interpreter ABI Platform Actions
dataone_auth-0.1.1-py3-none-any.whl Python 3 none any Details for dataone_auth-0.1.1-py3-none-any.whl

Total release size: 108.7 kB

Release files / dataone_auth-0.1.1.tar.gz

Download URL dataone_auth-0.1.1.tar.gz
Size 90.5 kB
Tags Source
SHA-256 checksum
How to use checksums
077655be635206a6d3e120237336b6d547364005f2f3a6e4473363539af36d22
BLAKE2b-256 checksum
How to use checksums
d34ed8bbe9fd203e22cf94a024f1aae438e72ac9807f7690e0305bc2cb5c3519
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / dataone_auth-0.1.1-py3-none-any.whl

Download URL dataone_auth-0.1.1-py3-none-any.whl
Size 18.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d69bacd4f52e8ed22d9f0e6f7883c0c43f3bdf6878a6fdcd0a5437472baecc48
BLAKE2b-256 checksum
How to use checksums
650016bd5876c5739ab0f3af58dff4984b497aca8415fd7036e1d223ecc461ed
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for dataone-auth 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dataone_auth-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page