diff --git a/kinde_fastapi/examples/README.md b/kinde_fastapi/examples/README.md index b585a26d..4cfc6550 100644 --- a/kinde_fastapi/examples/README.md +++ b/kinde_fastapi/examples/README.md @@ -6,7 +6,7 @@ This is an example FastAPI application that demonstrates how to use the Kinde Fa 1. Install the required dependencies: ```bash -pip install fastapi uvicorn jinja2 python-multipart +pip install fastapi uvicorn python-multipart python-dotenv ``` 2. Configure your Kinde application: @@ -14,17 +14,19 @@ pip install fastapi uvicorn jinja2 python-multipart - Set the redirect URI to `http://localhost:8000/callback` - Copy your client ID and client secret -3. Update the configuration in `example_app.py`: - - Replace `your_client_id` with your actual client ID - - Replace `your_client_secret` with your actual client secret - - Update the URLs to match your Kinde domain - - Change the session secret key to a secure value +3. Create a `.env` file in the examples directory with the following variables: +```env +KINDE_CLIENT_ID=your_client_id +KINDE_CLIENT_SECRET=your_client_secret +KINDE_REDIRECT_URI=http://localhost:8000/callback +KINDE_HOST=https://your-domain.kinde.com +``` ## Running the Example -Run the example application: +Run the example application from the SDK root directory: ```bash -python example_app.py +python -m uvicorn kinde_fastapi.examples.example_app:app --reload --port 8000 ``` The application will be available at `http://localhost:8000`. @@ -37,20 +39,30 @@ The application will be available at `http://localhost:8000`. - Session management - Logout -2. **Protected Routes** +2. **Automatic Route Registration** + - The OAuth class automatically registers these routes: + - `/login` - Redirects to Kinde login + - `/callback` - Handles OAuth callback from Kinde + - `/logout` - Logs out the user + - `/register` - Redirects to Kinde registration + - `/user` - Returns user information (JSON) + +3. **Protected Routes** - Example of a protected route that requires authentication - Automatic redirection to login for unauthenticated users -3. **User Information** +4. **User Information** - Retrieving and displaying user information - Session-based user state management ## API Endpoints - `/` - Home page (shows different content based on authentication status) -- `/login` - Redirects to Kinde login -- `/callback` - Handles OAuth callback from Kinde -- `/logout` - Logs out the user +- `/login` - Redirects to Kinde login (auto-registered) +- `/callback` - Handles OAuth callback from Kinde (auto-registered) +- `/logout` - Logs out the user (auto-registered) +- `/register` - Redirects to Kinde registration (auto-registered) +- `/user` - Returns user information as JSON (auto-registered) - `/protected` - Example protected route ## Security Considerations @@ -69,4 +81,4 @@ The application will be available at `http://localhost:8000`. 3. Add more security features 4. Use proper templates instead of inline HTML 5. Add user profile management -6. Implement role-based access control \ No newline at end of file +6. Implement role-based access control diff --git a/kinde_fastapi/examples/example_app.py b/kinde_fastapi/examples/example_app.py index 49bacafe..6431bee7 100644 --- a/kinde_fastapi/examples/example_app.py +++ b/kinde_fastapi/examples/example_app.py @@ -1,304 +1,143 @@ """ -SmartOAuth FastAPI Example Application +Kinde FastAPI Example Application -This example demonstrates how to use the new SmartOAuth client in a FastAPI application. -SmartOAuth automatically detects the execution context (sync vs async) and uses the -appropriate methods, providing a consistent API across different frameworks. +This example demonstrates how to use the Kinde OAuth client in a FastAPI application. +The OAuth class automatically registers authentication routes and handles the OAuth flow. Key Features Demonstrated: -- Automatic context detection (async in FastAPI) -- Both sync and async method usage -- Warning system for suboptimal usage -- Integration with auth modules (sync and async) -- Factory function usage -- Real-world authentication flow +- Simple OAuth setup with FastAPI +- Automatic route registration (/login, /logout, /callback, /register, /user) +- Authentication status checking +- User information retrieval Usage: -1. Set up your environment variables (see .env.example) -2. Run: python -m uvicorn kinde_fastapi.examples.example_app:app --reload -3. Visit http://localhost:5000 +1. Set up your environment variables in a .env file: + - KINDE_CLIENT_ID=your_client_id + - KINDE_CLIENT_SECRET=your_client_secret + - KINDE_REDIRECT_URI=http://localhost:8000/callback + - KINDE_HOST=https://your-domain.kinde.com + +2. Run from the SDK root directory: + python -m uvicorn kinde_fastapi.examples.example_app:app --reload --port 8000 + +3. Visit http://localhost:8000 + +Available Routes (automatically registered): +- /login - Redirects to Kinde login +- /logout - Logs out the user +- /callback - Handles OAuth callback +- /register - Redirects to Kinde registration +- /user - Returns user information (redirects to login if not authenticated) """ -from fastapi import FastAPI, Request -from fastapi.responses import HTMLResponse -from starlette.middleware.sessions import SessionMiddleware +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, RedirectResponse from .session import InMemorySessionMiddleware -from pathlib import Path import os +import html from dotenv import load_dotenv import logging -from kinde_sdk import SmartOAuth, create_oauth_client -from kinde_sdk.auth import claims, feature_flags, permissions, tokens, async_claims -from kinde_sdk.management import ManagementClient; -from kinde_sdk.management.management_token_manager import ManagementTokenManager -import requests +from kinde_sdk.auth.oauth import OAuth logger = logging.getLogger(__name__) -# Load environment variables from .env file -load_dotenv() +# Load environment variables from .env file located alongside this script +load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) # Initialize FastAPI app app = FastAPI(title="Kinde FastAPI Example") # Add session middleware with proper configuration +# This is required for storing session data between requests app.add_middleware( InMemorySessionMiddleware, max_age=3600, # 1 hour https_only=False ) -# Initialize Kinde SmartOAuth with FastAPI framework -# SmartOAuth automatically detects the async context and uses the appropriate methods -kinde_oauth = SmartOAuth( +# Initialize Kinde OAuth with FastAPI framework +# This automatically registers /login, /logout, /callback, /register, /user routes +kinde_oauth = OAuth( framework="fastapi", app=app ) -# Alternative: You can also use the factory function -# kinde_oauth = create_oauth_client( -# async_mode=None, # None means auto-detect (SmartOAuth) -# framework="fastapi", -# app=app -# ) - # Example home route @app.get("/", response_class=HTMLResponse) -async def home(request: Request): +async def home(): """ Home page that shows different content based on authentication status. """ if kinde_oauth.is_authenticated(): - # In FastAPI (async context), SmartOAuth will use async methods automatically - # You can use either sync or async methods - SmartOAuth will handle the context - - # Option 1: Use async methods (recommended in async context) - user_async = await kinde_oauth.get_user_info_async() - - # Use the async version for better performance - user = user_async - - # Validate environment variables - domain = os.getenv("KINDE_DOMAIN") - client_id = os.getenv("KINDE_MANAGEMENT_CLIENT_ID") - client_secret = os.getenv("KINDE_MANAGEMENT_CLIENT_SECRET") - - if not all([domain, client_id, client_secret]): - return """ + try: + user = kinde_oauth.get_user_info() + email = html.escape(user.get('email', 'User')) + email_display = html.escape(user.get('email', 'N/A')) + given_name = html.escape(user.get('given_name', '')) + family_name = html.escape(user.get('family_name', '')) + user_id = html.escape(user.get('sub', 'N/A')) + return f"""
-Missing required environment variables for management client.
- Logout +You are logged in.
+User Info (async): {user.get('email')}
-Claims (sync): {claims_sync}
-Claims (async): {claims_async}
-Feature Flags: {feature_flags_data}
-Permissions: {permissions_data}
-Access Token: {access_token[:20]}...
-Management Users: {user_count} user(s) found
-Note: SmartOAuth automatically detected the async context and used async methods.
-You are logged in.
-Failed to get user information: {error_msg}
+ Logout + + + """ + return """ -You are not logged in.
-This example demonstrates SmartOAuth in a FastAPI application.
- Login with SmartOAuth +This example demonstrates Kinde OAuth integration with FastAPI.
+ - +