{"id":29874993,"url":"https://github.com/iaalm/fastapi_simple_oauth2","last_synced_at":"2026-05-15T21:05:31.397Z","repository":{"id":305159444,"uuid":"1022009763","full_name":"iaalm/fastapi_simple_oauth2","owner":"iaalm","description":"A lightweight, stateless OAuth2 middleware for FastAPI applications with PKCE flow support.","archived":false,"fork":false,"pushed_at":"2025-07-19T13:08:46.000Z","size":192,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-31T02:34:22.235Z","etag":null,"topics":["fastapi","oauth2","pkce"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/iaalm.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-18T09:55:37.000Z","updated_at":"2025-07-19T13:08:50.000Z","dependencies_parsed_at":"2025-07-18T17:50:29.254Z","dependency_job_id":"2089be80-38ec-484a-8793-00b5ae03be39","html_url":"https://github.com/iaalm/fastapi_simple_oauth2","commit_stats":null,"previous_names":["iaalm/fastapi_simple_oauth2"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/iaalm/fastapi_simple_oauth2","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iaalm%2Ffastapi_simple_oauth2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iaalm%2Ffastapi_simple_oauth2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iaalm%2Ffastapi_simple_oauth2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iaalm%2Ffastapi_simple_oauth2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/iaalm","download_url":"https://codeload.github.com/iaalm/fastapi_simple_oauth2/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iaalm%2Ffastapi_simple_oauth2/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":271594379,"owners_count":24786707,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-22T02:00:08.480Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","oauth2","pkce"],"created_at":"2025-07-31T01:46:27.711Z","updated_at":"2026-05-15T21:05:26.376Z","avatar_url":"https://github.com/iaalm.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Simple OAuth2 PKCE\n\nA lightweight, stateless OAuth2 middleware for FastAPI applications with PKCE (Proof Key for Code Exchange) flow support. This plugin provides a simple way to implement OAuth2 authorization in your FastAPI applications without the complexity of full OAuth2 providers.\n\n## Features\n\n- **PKCE Flow Support**: Implements OAuth2 PKCE flow for secure authorization\n- **JWT Tokens**: Stateless authentication using JWT tokens\n- **Custom Claims**: Support for custom claims in JWT tokens\n- **Simple Integration**: Easy to integrate with existing FastAPI applications\n- **Single Tenant**: Target to inline intergrated with your application easily, no multi-tenantcy support\n- **No Database Required**: In-memory storage for development (can be extended for production)\n\n## Installation\n\n```bash\npip install fastapi-simple-oauth2\n```\n\n## Quick Start\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_simple_oauth2 import register_oauth_route, require_claim\n\napp = FastAPI()\n\n# Define your user validation function\ndef validate_user(username: str, password: str):\n    # Your authentication logic here\n    if username == \"admin\" and password == \"password\":\n        return {\"user_id\": \"admin\", \"role\": \"admin\"}\n    return None\n\n# Register OAuth routes\noauth = register_oauth_route(app, validate_callback=validate_user)\n\n# Protected endpoint\n@app.get(\"/protected\")\n@require_claim({\"role\": \"admin\"})\nasync def protected_route():\n    return {\"message\": \"Access granted!\"}\n```\n\n## API Reference\n\n### `register_oauth_route(app, validate_callback, key=None)`\n\nRegisters OAuth2 routes with your FastAPI application.\n\n**Parameters:**\n- `app` (FastAPI): Your FastAPI application instance\n- `validate_callback` (Callable): Function that validates username/password and returns claims\n- `key` (str, optional): Secret key for JWT signing. If not provided, a random key will be generated.\n\n**Returns:**\n- `OAuth2PKCE`: OAuth2 instance for further configuration\n\n### `require_claims_dependency(required_claims)`\n\nDecorator to protect endpoints with specific claim requirements.\n\n**Parameters:**\n- `require_claims_dependency` (dict): Dictionary of required claims and their expected values\n\n## OAuth2 Flow\n\n### 1. Authorization Request\n\nThe client initiates the OAuth2 flow by redirecting the user to the `/authorize` endpoint:\n\n```\nGET /authorize?response_type=code\u0026redirect_uri=http://localhost:3000/callback\u0026code_challenge=YOUR_CODE_CHALLENGE\u0026code_challenge_method=S256\u0026state=random_state\n```\n\n**Required Parameters:**\n- `response_type`: Must be \"code\"\n- `redirect_uri`: Where to redirect after authorization\n- `code_challenge`: PKCE code challenge\n- `code_challenge_method`: Must be \"S256\"\n\n### 2. User Authentication\n\nThe user is redirected to your application where they can authenticate. After successful authentication, the user is redirected back with an authorization code.\n\n### 3. Token Exchange\n\nThe client exchanges the authorization code for an access token:\n\n```\nPOST /token\nContent-Type: application/x-www-form-urlencoded\n\ngrant_type=authorization_code\u0026code=AUTHORIZATION_CODE\u0026code_verifier=CODE_VERIFIER\u0026redirect_uri=http://localhost:3000/callback\n```\n\n**Response:**\n```json\n{\n    \"access_token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 3600\n}\n```\n\n### 4. Using the Access Token\n\nInclude the access token in the Authorization header for protected endpoints:\n\n```\nAuthorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...\n```\n\n## Example Usage\n\n### Basic Setup\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_simple_oauth2 import register_oauth_route, require_claim\n\napp = FastAPI()\n\n# Mock user database\nUSERS = {\n    \"admin\": {\"password\": \"admin123\", \"claims\": {\"role\": \"admin\"}},\n    \"user\": {\"password\": \"user123\", \"claims\": {\"role\": \"user\"}}\n}\n\ndef validate_user(username: str, password: str):\n    user = USERS.get(username)\n    if user and user[\"password\"] == password:\n        return user[\"claims\"]\n    return None\n\n# Register OAuth routes\noauth = register_oauth_route(app, validate_callback=validate_user)\n\n# Protected endpoints\n@app.get(\"/admin\")\n@require_claim({\"role\": \"admin\"})async def admin_only(\n    user_cliaims: ClaimsSet = Depends(\n        oauth.require_claims_dependency({\"role\": \"admin\"})\n    ),\n) -\u003e Any:\n    return {\"message\": \"Admin access granted!\", \"data\": \"sensitive admin data\"}\n\n@app.get(\"/data\")\nasync def read_data(\n    user_cliaims: ClaimsSet = Depends(\n        oauth.require_claims_dependency({\"permissions\": [\"read\"]})\n    ),\n) -\u003e Any:\n    return {\"message\": \"Data access granted!\", \"data\": \"some data\"}\n```\n\n### Frontend Integration\n\nHere's an example of how to implement the OAuth2 flow in a frontend application:\n\n```javascript\n// Generate PKCE code verifier and challenge\nfunction generateCodeVerifier() {\n    const array = new Uint8Array(32);\n    crypto.getRandomValues(array);\n    return base64URLEncode(array);\n}\n\nfunction generateCodeChallenge(verifier) {\n    const hash = crypto.subtle.digestSync('SHA-256', new TextEncoder().encode(verifier));\n    return base64URLEncode(new Uint8Array(hash));\n}\n\n// Start OAuth2 flow\nasync function startOAuthFlow() {\n    const codeVerifier = generateCodeVerifier();\n    const codeChallenge = generateCodeChallenge(codeVerifier);\n    \n    // Store code verifier for later use\n    localStorage.setItem('code_verifier', codeVerifier);\n    \n    const params = new URLSearchParams({\n        response_type: 'code',\n        redirect_uri: 'http://localhost:3000/callback',\n        code_challenge: codeChallenge,\n        code_challenge_method: 'S256',\n        state: generateRandomState()\n    });\n    \n    window.location.href = `http://localhost:8000/authorize?${params}`;\n}\n\n// Exchange code for token\nasync function exchangeCodeForToken(code) {\n    const codeVerifier = localStorage.getItem('code_verifier');\n    \n    const response = await fetch('http://localhost:8000/token', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/x-www-form-urlencoded',\n        },\n        body: new URLSearchParams({\n            grant_type: 'authorization_code',\n            code: code,\n            code_verifier: codeVerifier,\n            redirect_uri: 'http://localhost:3000/callback'\n        })\n    });\n    \n    const tokenData = await response.json();\n    localStorage.setItem('access_token', tokenData.access_token);\n}\n```\n\n## License\n\nMIT License - see LICENSE file for details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiaalm%2Ffastapi_simple_oauth2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fiaalm%2Ffastapi_simple_oauth2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiaalm%2Ffastapi_simple_oauth2/lists"}