fastapi-simple-oidc


Namefastapi-simple-oidc JSON
Version 0.0.3 PyPI version JSON
download
home_pageNone
SummaryOIDC for FastAPI
upload_time2025-02-26 22:53:37
maintainerNone
docs_urlNone
authorNone
requires_pythonNone
licenseNone
keywords fastapi sso
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # OpenID Connect Plugin for FastAPI

**fastapi-simple-oidc** is a simple, configurable plugin for enabling OpenID Connect (OIDC) authentication in a FastAPI application. It supports multiple identity providers, session management, and callbacks for handling login and logout events.

## Features

- **OpenID Connect (OIDC)** integration for authentication.
- Support for popular Identity Providers like Google, Microsoft, Apple, GitLab, Salesforce, and IBM.
- Support for any custom OIDC backend.
- Easy provider discovery using `.well-known/openid-configuration`.
- Session-based user management using `SessionMiddleware`.
- Callbacks for `on_login` and `on_logout` to customize user handling behavior.
- Pre-built routes for login, logout, user information, and provider discovery.
- Extendable to additional identity providers.

---

## Installation

```bash
pip install fastapi-simple-oidc
```

---

## Quick Start

Here’s a quick guide to get you started with FastAPI and OIDC.

### 1. Setup your FastAPI application

```python
from fastapi import FastAPI
from fastapi_oidc import OIDC

app = FastAPI()

# Create an OIDC instance
oidc = OIDC(
    app=app,
    secret_key="your-session-secret",  # A secure key for the application session
    login_url='/login',                # Optional: Redirect URL for login page
    redirect_url='/dashboard'          # Optional: URL to redirect to after login
)

# Register OIDC routes
app.include_router(oidc.router)
```

---

### 2. Configure Identity Providers

Identity provider configurations must be set using environment variables or configuration files.

#### Environment Variable Example:

```env
SSO_GOOGLE_ID=<google-client-id>
SSO_GOOGLE_SECRET=<google-client-secret>

SSO_MICROSOFT_ID=<microsoft-client-id>
SSO_MICROSOFT_SECRET=<microsoft-client-secret>
SSO_GOOGLE_NAME=Custom Google Name  # Optional: Display name for Google

# also Custom Provider
SSO_CUSTOM_ID=
SSO_CUSTOM_SECRET=
SSO_CUSTOM_URL=
SSO_CUSTOM_NAME=
```

#### Built-in Identity Providers

The library supports the following providers out of the box, you don't need to specify `NAME` and `URL`

- Google
- Microsoft
- Apple
- GitLab
- Salesforce
- IBM

---

### 3. Add Login and Logout Callbacks (Optional)

You can define custom logic that runs after login or logout events using the `on_login` and `on_logout` decorators.

```python
from fastapi_oidc import OpenID

@oidc.on_login
def handle_login(user: OpenID):
    print(f"User logged in: {user.name} ({user.email})")

@oidc.on_logout
def handle_logout(user: OpenID):
    print(f"User logged out: {user.email}")
```

---

### 4. Secure Your Routes with Authentication

Use the `get_logged_user` dependency to secure your endpoints and access the currently authorized user.

```python
from fastapi_oidc import get_logged_user, OpenID

@app.get("/protected")
async def protected_endpoint(user: OpenID = Depends(get_logged_user)):
    return {"message": f"Welcome {user.name}", "email": user.email}
```

Exception raised for unauthorized users:
- **401 Unauthorized**: If the user is not authenticated.

---

### 5. Test the Integration

Visit the built-in test page at the `/.test` route to verify the setup:
- List all available Identity Providers.
- Attempt login/logout.
- Check the current session.

![alt text](img.png)
---

## Routes

The plugin automatically registers the following routes:

| **Route**              | **Description**                                                              |
|------------------------|------------------------------------------------------------------------------|
| `/<provider>/login`    | Login redirection page.                                                      |
| `/<provider>/callback` | OIDC callback                                                                |
| `/logout`              | Clears the session and logs the user out.                                    |
| `/me`                  | Returns the details of the currently logged-in user. Uses `get_logged_user`. |
| `/providers`           | Lists all available identity providers.                                      |
| `/.test`               | A pre-built test page to test your OIDC configuration.                       |

Each Identity Provider will also have its own login and callback routes under `<provider>/login` and `<provider>/callback`.

---

## Environment Variables Reference

The following environment variables can be set to configure available identity providers:

| **Variable**                | **Required**                          | **Description**                                           |
|-----------------------------|---------------------------------------|-----------------------------------------------------------|
| `SSO_<PROVIDER>_ID`         | Yes                                  | The client ID for the identity provider.                  |
| `SSO_<PROVIDER>_SECRET`     | Yes                                  | The client secret for the identity provider.              |
| `SSO_<PROVIDER>_URL`        | Only if not a default provider       | The OpenID Connect discovery URL of the identity provider.|
| `SSO_<PROVIDER>_NAME`       | No                                   | Custom display name for the provider in `/providers`.     |

---

## Extending

### Add New Providers

You can integrate custom providers by adding their configuration into environment variables as shown earlier. The package uses the `.well-known/openid-configuration` standard to fetch OpenID Connect metadata, so the provider needs to follow this specification.

---

## Example App

Here’s an example app using Google as an Identity Provider:

```python
from fastapi import FastAPI, Depends
from fastapi_oidc import OIDC, get_logged_user, OpenID

app = FastAPI()

oidc = OIDC(
    app=app,
    secret_key="random-secret-key",
    login_url='/login',
    redirect_url='/dashboard'
)

# Register OIDC routes
app.include_router(oidc.router)

# Secure route
@app.get("/dashboard")
async def dashboard(user: OpenID = Depends(get_logged_user)):
    return {"message": f"Hello, {user.name}!", "email": user.email}

@oidc.on_login
def handle_login(user: OpenID):
    print(f"User logged in: {user.email}")

@oidc.on_logout
def handle_logout(user: OpenID):
    print(f"User logged out: {user.email}")
```

---

### Supported Defaults

When using the default providers, you don’t need to define URLs; they are managed internally.

---

## License

This project is licensed under the MIT License.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-simple-oidc",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "fastapi, sso",
    "author": null,
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/40/5f/6976c0fca6efb704727388155d328e17433704eee34702a0b6f739cb00d9/fastapi_simple_oidc-0.0.3.tar.gz",
    "platform": null,
    "description": "# OpenID Connect Plugin for FastAPI\n\n**fastapi-simple-oidc** is a simple, configurable plugin for enabling OpenID Connect (OIDC) authentication in a FastAPI application. It supports multiple identity providers, session management, and callbacks for handling login and logout events.\n\n## Features\n\n- **OpenID Connect (OIDC)** integration for authentication.\n- Support for popular Identity Providers like Google, Microsoft, Apple, GitLab, Salesforce, and IBM.\n- Support for any custom OIDC backend.\n- Easy provider discovery using `.well-known/openid-configuration`.\n- Session-based user management using `SessionMiddleware`.\n- Callbacks for `on_login` and `on_logout` to customize user handling behavior.\n- Pre-built routes for login, logout, user information, and provider discovery.\n- Extendable to additional identity providers.\n\n---\n\n## Installation\n\n```bash\npip install fastapi-simple-oidc\n```\n\n---\n\n## Quick Start\n\nHere\u2019s a quick guide to get you started with FastAPI and OIDC.\n\n### 1. Setup your FastAPI application\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_oidc import OIDC\n\napp = FastAPI()\n\n# Create an OIDC instance\noidc = OIDC(\n    app=app,\n    secret_key=\"your-session-secret\",  # A secure key for the application session\n    login_url='/login',                # Optional: Redirect URL for login page\n    redirect_url='/dashboard'          # Optional: URL to redirect to after login\n)\n\n# Register OIDC routes\napp.include_router(oidc.router)\n```\n\n---\n\n### 2. Configure Identity Providers\n\nIdentity provider configurations must be set using environment variables or configuration files.\n\n#### Environment Variable Example:\n\n```env\nSSO_GOOGLE_ID=<google-client-id>\nSSO_GOOGLE_SECRET=<google-client-secret>\n\nSSO_MICROSOFT_ID=<microsoft-client-id>\nSSO_MICROSOFT_SECRET=<microsoft-client-secret>\nSSO_GOOGLE_NAME=Custom Google Name  # Optional: Display name for Google\n\n# also Custom Provider\nSSO_CUSTOM_ID=\nSSO_CUSTOM_SECRET=\nSSO_CUSTOM_URL=\nSSO_CUSTOM_NAME=\n```\n\n#### Built-in Identity Providers\n\nThe library supports the following providers out of the box, you don't need to specify `NAME` and `URL`\n\n- Google\n- Microsoft\n- Apple\n- GitLab\n- Salesforce\n- IBM\n\n---\n\n### 3. Add Login and Logout Callbacks (Optional)\n\nYou can define custom logic that runs after login or logout events using the `on_login` and `on_logout` decorators.\n\n```python\nfrom fastapi_oidc import OpenID\n\n@oidc.on_login\ndef handle_login(user: OpenID):\n    print(f\"User logged in: {user.name} ({user.email})\")\n\n@oidc.on_logout\ndef handle_logout(user: OpenID):\n    print(f\"User logged out: {user.email}\")\n```\n\n---\n\n### 4. Secure Your Routes with Authentication\n\nUse the `get_logged_user` dependency to secure your endpoints and access the currently authorized user.\n\n```python\nfrom fastapi_oidc import get_logged_user, OpenID\n\n@app.get(\"/protected\")\nasync def protected_endpoint(user: OpenID = Depends(get_logged_user)):\n    return {\"message\": f\"Welcome {user.name}\", \"email\": user.email}\n```\n\nException raised for unauthorized users:\n- **401 Unauthorized**: If the user is not authenticated.\n\n---\n\n### 5. Test the Integration\n\nVisit the built-in test page at the `/.test` route to verify the setup:\n- List all available Identity Providers.\n- Attempt login/logout.\n- Check the current session.\n\n![alt text](img.png)\n---\n\n## Routes\n\nThe plugin automatically registers the following routes:\n\n| **Route**              | **Description**                                                              |\n|------------------------|------------------------------------------------------------------------------|\n| `/<provider>/login`    | Login redirection page.                                                      |\n| `/<provider>/callback` | OIDC callback                                                                |\n| `/logout`              | Clears the session and logs the user out.                                    |\n| `/me`                  | Returns the details of the currently logged-in user. Uses `get_logged_user`. |\n| `/providers`           | Lists all available identity providers.                                      |\n| `/.test`               | A pre-built test page to test your OIDC configuration.                       |\n\nEach Identity Provider will also have its own login and callback routes under `<provider>/login` and `<provider>/callback`.\n\n---\n\n## Environment Variables Reference\n\nThe following environment variables can be set to configure available identity providers:\n\n| **Variable**                | **Required**                          | **Description**                                           |\n|-----------------------------|---------------------------------------|-----------------------------------------------------------|\n| `SSO_<PROVIDER>_ID`         | Yes                                  | The client ID for the identity provider.                  |\n| `SSO_<PROVIDER>_SECRET`     | Yes                                  | The client secret for the identity provider.              |\n| `SSO_<PROVIDER>_URL`        | Only if not a default provider       | The OpenID Connect discovery URL of the identity provider.|\n| `SSO_<PROVIDER>_NAME`       | No                                   | Custom display name for the provider in `/providers`.     |\n\n---\n\n## Extending\n\n### Add New Providers\n\nYou can integrate custom providers by adding their configuration into environment variables as shown earlier. The package uses the `.well-known/openid-configuration` standard to fetch OpenID Connect metadata, so the provider needs to follow this specification.\n\n---\n\n## Example App\n\nHere\u2019s an example app using Google as an Identity Provider:\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom fastapi_oidc import OIDC, get_logged_user, OpenID\n\napp = FastAPI()\n\noidc = OIDC(\n    app=app,\n    secret_key=\"random-secret-key\",\n    login_url='/login',\n    redirect_url='/dashboard'\n)\n\n# Register OIDC routes\napp.include_router(oidc.router)\n\n# Secure route\n@app.get(\"/dashboard\")\nasync def dashboard(user: OpenID = Depends(get_logged_user)):\n    return {\"message\": f\"Hello, {user.name}!\", \"email\": user.email}\n\n@oidc.on_login\ndef handle_login(user: OpenID):\n    print(f\"User logged in: {user.email}\")\n\n@oidc.on_logout\ndef handle_logout(user: OpenID):\n    print(f\"User logged out: {user.email}\")\n```\n\n---\n\n### Supported Defaults\n\nWhen using the default providers, you don\u2019t need to define URLs; they are managed internally.\n\n---\n\n## License\n\nThis project is licensed under the MIT License.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "OIDC for FastAPI",
    "version": "0.0.3",
    "project_urls": {
        "Homepage": "https://github.com/levy42/fastapi-simple-oidc",
        "Repository": "https://github.com/levy42/fastapi-simple-oidc"
    },
    "split_keywords": [
        "fastapi",
        " sso"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "5df8bbbd58c0b89cecc0ea9eae141373008afb9c41d8f4534bc9998cf94f130c",
                "md5": "7f2dac01e13738637011890776207b00",
                "sha256": "0fb07e36784c35dde54e335f35f2034e9571aa4b571b13169d5291dbb83643cb"
            },
            "downloads": -1,
            "filename": "fastapi_simple_oidc-0.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7f2dac01e13738637011890776207b00",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 7777,
            "upload_time": "2025-02-26T22:53:36",
            "upload_time_iso_8601": "2025-02-26T22:53:36.165403Z",
            "url": "https://files.pythonhosted.org/packages/5d/f8/bbbd58c0b89cecc0ea9eae141373008afb9c41d8f4534bc9998cf94f130c/fastapi_simple_oidc-0.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "405f6976c0fca6efb704727388155d328e17433704eee34702a0b6f739cb00d9",
                "md5": "2788c235808baac1e7e2accda710b94f",
                "sha256": "13e501e51d0e3ba1b05cf5b5a4ec58ea0f6d419918a9c76048f4231aad6d702d"
            },
            "downloads": -1,
            "filename": "fastapi_simple_oidc-0.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "2788c235808baac1e7e2accda710b94f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 7127,
            "upload_time": "2025-02-26T22:53:37",
            "upload_time_iso_8601": "2025-02-26T22:53:37.523992Z",
            "url": "https://files.pythonhosted.org/packages/40/5f/6976c0fca6efb704727388155d328e17433704eee34702a0b6f739cb00d9/fastapi_simple_oidc-0.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-02-26 22:53:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "levy42",
    "github_project": "fastapi-simple-oidc",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-simple-oidc"
}
        
Elapsed time: 0.41445s