FastAPI authlib OpenID integration
Project description
fastapi-authlib-oidc
FastAPI OpenID authlib integration
Installation
pip install fastapi-authlib-oidc
Setup
- Secrets:
client_id: CLIENT_ID
client_secret: CLIENT_SECRET
issuer: IDP_ISSUER <url before /.well-known/openid-configuration>
- Base login configuration
import json
import logging
from fastapi import FastAPI, Depends, status, HTTPException
from fastapi.responses import JSONResponse
from fastapi.requests import Request
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from fastapi_oidc import FastAPIOIDC
from typing import Annotated
from starlette.datastructures import FormData
from pydantic import BaseModel
app = FastAPI()
app.extra.update(
{
"OIDC_CLIENT_SECRETS": "config/secrets.yml",
"OIDC_OPENID_REALM": "OPENID",
"OIDC_SCOPES": "openid email",
"OIDC_INTROSPECTION_AUTH_METHOD": "client_secret_post",
"OIDC_USER_INFO_ENABLED": True
}
)
oidc = FastAPIOIDC(app)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class NotFound(BaseModel):
details: str
async def authenticate(request: Annotated[Request, Depends()], ) -> JSONResponse:
form_data: FormData = await request.form()
user = oidc.token(form_data)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
)
return JSONResponse(content=json.loads(user.get_id()), status_code=status.HTTP_200_OK)
@app.get('/api/test/')
def index(token: Annotated[str, Depends(oauth2_scheme)]):
logging.warning(oidc.user(token).email)
return NotFound(details='Empty')
app.add_route(path='/token', route=authenticate, methods=["POST"], name='authenticate')
- Custom login configuration
import json
import logging
from fastapi import FastAPI, Depends, status, HTTPException
from fastapi.responses import JSONResponse
from fastapi.requests import Request
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from fastapi_oidc import FastAPIOIDC
from typing import Annotated
from starlette.datastructures import FormData
from pydantic import BaseModel
app = FastAPI()
app.extra.update(
{
"SSO_CLIENT_SECRETS": "config/secrets.yml",
"SSO_OPENID_REALM": "OPENID",
"SSO_SCOPES": "openid email",
"SSO_INTROSPECTION_AUTH_METHOD": "client_secret_post",
"SSO_USER_INFO_ENABLED": True
}
)
oidc = FastAPIOIDC(app, prefix='SSO')
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class NotFound(BaseModel):
details: str
async def authenticate(request: Annotated[Request, Depends()], ) -> JSONResponse:
form_data: FormData = await request.form()
user = oidc.token(form_data)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
)
return JSONResponse(content=json.loads(user.get_id()), status_code=status.HTTP_200_OK)
@app.get('/api/test/')
def index(token: Annotated[str, Depends(oauth2_scheme)]):
logging.warning(oidc.user(token).email)
return NotFound(details='Empty')
app.add_route(path='/token', route=authenticate, methods=["POST"], name='authenticate')
Using custom user model
Must be used after FastAPIOIDC.init_app() or FastAPIOIDC() if you are not using it
oidc.user_model(UserModel)
See [user.py](https://github.com/frederickney/fastapi_authlib_oidc/blob/master/fastapi_oidc/user.py for more information about user model
Custom login
Must be used after FastAPIOIDC.init_app() or FastAPIOIDC() if you are not using it
def login(oidc_auth, model, token=None, user=None, password=None):
"""
:param oidc_auth: oauth client
:type oidc_auth: OAuth2Mixin
:param model: user model
:param token: user's oauth tokens
:type token: dict[str, any]
:param user: username
:type user: str
:param password: user's password
:type password: str
:return:
"""
pass
oidc.login_user(login)
Custom client
Must be used after FastAPIOIDC.init_app() or FastAPIOIDC() if you are not using it
def client(prefix):
"""
:param prefix:
:type prefix: str
:return:
:rtype: OAuth2Mixin
"""
pass
oidc.client(client)
Custom secret load
Must be used after FastAPIOIDC.init_app() or FastAPIOIDC() if you are not using it
def secret(app, prefix):
"""
:param app:
:type app: flask.Flask
:param prefix:
:type prefix:str
:return:
:rtype: dict
"""
pass
oidc.secret(secret)
Enjoy
LICENSE
See License file
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_authlib_oidc-1.0.2.tar.gz.
File metadata
- Download URL: fastapi_authlib_oidc-1.0.2.tar.gz
- Upload date:
- Size: 45.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bf40b313ab01fd6e6d249e524b5564ea81e5ee0f963601e2c6aaecc867eaaad4
|
|
| MD5 |
1246cbdc1558452c1bc09fddfe75f264
|
|
| BLAKE2b-256 |
ab1a770e5c2484066a762fbe7ebab9f41918c91688f7913a0bdef3067234ae09
|
File details
Details for the file fastapi_authlib_oidc-1.0.2-py3-none-any.whl.
File metadata
- Download URL: fastapi_authlib_oidc-1.0.2-py3-none-any.whl
- Upload date:
- Size: 34.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5c414adbf29e2d635ae48b48101952d8b55e2913bd466f10c577053f406a34e1
|
|
| MD5 |
afa04a428e5b3f86652f51ac00a7f87b
|
|
| BLAKE2b-256 |
80f1845e5bc132864fc10abf40a28ab230914d9767e801ae3381c5887f3fa6ff
|