Skip to main content

Python plugins for the Authup authentication and authorization framework

Project description

CI codecov Code style: black

Authup Python Plugins

This repository contains python plugins for using the Authup authentication and authorization framework in the python language. The plugins are used to integrate Authup with different python frameworks and libraries.

Supported Python frameworks

Client

Plugin Extra Sync Async
httpx
requests [requests]

Server

Plugin Extra Sync Async Middleware User
FastApi [fastapi]
ASGI [asgi]
Flask [flask]

Installation

The plugins are available via PyPi.

pip install authup-py

Extra dependencies

The plugin for the project's base library httpx need no extra dependencies. To use the additional plugins for other libraries, you need to install with the corresponding extra i.e. for requests:

pip install authup-py[requests]

How to use

All the plugins share the underlying Authup class. The class is initialized with the url of the Authup server and the credentials you would like to use (username/password or robot_id/secret).
The class provides both sync and async methods for the different authentication and authorization flows.

from authup import Authup

authup = Authup(
    url="https://authup.org",
    username="username",
    password="password"
)

authup_robot = Authup(
    url="https://authup.org",
    robot_id="robot",
    robot_secret="secret"
)

The following plugins all expect the same arguments as the Authup class with the addition of the app as a first argument for server side libraries (e.g. FastApi, Flask).

httpx

For synchronously using the plugin with httpx , you can use the AuthupHttpx class and pass an instance to your httpx.Client or a basic httpx.Request as the auth parameter:

import httpx
from authup.plugins.httpx import AuthupHttpx

authup = AuthupHttpx(
    url="https://authup.org",
    username="username",
    password="password",
)

# Use the authup instance as the auth parameter for the httpx client
client = httpx.Client(auth=authup)

with client:
    response = client.get("https://authup.org")
    print(response.status_code)


# Use the authup instance as the auth parameter for a top level request function
request = httpx.get("https://authup.org", auth=authup)

It works the same way for the asynchronous httpx client:

import httpx
from authup.plugins.httpx import AuthupHttpxAsync

authup = AuthupHttpxAsync(
    url="https://authup.org",
    username="username",
    password="password",
)

async with httpx.AsyncClient(auth=authup) as client:
    response = await client.get("https://authup.org")
    print(response.status_code)

requests

Since requests is a synchronous library, the plugin is also synchronous. You can use the AuthupRequests class and use it with the requests.Session or the requests.request functions:

Note Requires the requests extra to be installed. pip install authup-py[requests]

import requests
from authup.plugins.requests import AuthupRequests

authup = AuthupRequests(
    url="https://authup.org",
    username="username",
    password="password",
)

# Use the authup instance as the auth parameter for the requests session
with requests.Session() as session:
    session.auth = authup
    response = session.get("https://authup.org")
    print(response.status_code)

# Use the authup instance as the auth parameter for a top level request function
response = requests.get("https://authup.org", auth=authup)
print(response.status_code)

ASGI Middleware

The AuthupASGIMiddleware class can be used as an ASGI middleware for any ASGI framework (i.e. FastAPI, Starlette). The middleware will check the incoming requests for a valid token and otherwise return a 401 response. If you pass the optional user parameter, the middleware will inject the user object into the request scope (r.state.user).

The first argument is the ASGI application and the second argument is the URL of the authup instance.

Note Requires the asgi extra to be installed. pip install authup-py[asgi]

The following shows a simple example for using the middleware with a FastAPI application but it should work with any ASGI framework.

Note Expects a running authup instance available at the given URL.

from fastapi import FastAPI
from authup.plugins.asgi import AuthupASGIMiddleware

app = FastAPI()

authup_url = "https://authup.org"  # change to your authup instance
@app.get("/test")
async def test():
    return {"message": "Hello World"}

# register the middleware pass the authup url as argument
app.add_middleware(AuthupASGIMiddleware, authup_url=authup_url)

Now you can access the /test endpoint without a token and will receive a 401 response. When using a valid token, you will receive the expected response.

import httpx
from authup.plugins.httpx import AuthupHttpx

# no token or invalid token raises 401
response = httpx.get("http://localhost:8000/test") # 401
print(response.status_code)

# valid token receives the expected response
authup = AuthupHttpx(
    url="https://authup.org",
    username="username",
    password="password",
)

response = httpx.get("http://localhost:8000/test", auth=authup) # 200
print(response.status_code)

Optional user injection

Set the user parameter to True when adding the middleware to your ASGI application:

from fastapi import FastAPI, Request
from authup.plugins.asgi import AuthupASGIMiddleware

app = FastAPI()

authup_url = "https://authup.org"  # change to your authup instance
@app.get("/test-user")
async def test(request: Request):
    return {"user": request.state.user}

# register the middleware pass the authup url as argument
app.add_middleware(AuthupASGIMiddleware, authup_url=authup_url, user=True)

Calling the /test-user endpoint without a token will return a 401 response. When using a valid token, the user object will be injected into the request scope, and you will receive the expected response containing your user.

FastAPI Dependency

The AuthupUser class can be used as a FastAPI dependency. It will check the incoming requests for a valid token and otherwise return a 401 response. If the token is valid a user object will be available in the dependency call.

Basic user dependency

The following shows a simple example for using the dependency with a FastAPI application that will return the user object obtained from the token.

from fastapi import FastAPI, Depends
from authup.plugins.fastapi import AuthupUser
from authup import User


app = FastAPI()

user_dependency = AuthupUser(url="http://localhost:3010")

@app.get("/test")
async def user_test(user: User = Depends(user_dependency)):
    return {"user": user.dict()}

Require permissions

You can also require specific permissions for the user. The following example will only allow users with the client_add permission and a power level of over 100. Otherwise, a 401 response will be returned.

from fastapi import FastAPI, Depends
from authup.plugins.fastapi import UserPermissions
from authup import User, Permission

permissions = [
        Permission(name="client_add", inverse=False, power=100),
    ]

required_permissions = UserPermissions(
    url="http://localhost:3010",
    permissions=permissions,
)

app = FastAPI()

@app.get("/test")
async def user_test(user: User = Depends(required_permissions)):
    return {"user": user.dict()}

How to develop

Install

Requires poetry and pre-commit and python 3.7+.

poetry install --with dev --all-extras

Install pre-commit hooks

pre-commit install

Test

poetry run pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

authup-0.3.0.tar.gz (13.7 kB view details)

Uploaded Source

Built Distribution

authup-0.3.0-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file authup-0.3.0.tar.gz.

File metadata

  • Download URL: authup-0.3.0.tar.gz
  • Upload date:
  • Size: 13.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.9.9 Windows/10

File hashes

Hashes for authup-0.3.0.tar.gz
Algorithm Hash digest
SHA256 1e38e7a4b134313dd062871090e9a429242f3b87fcf7dc39f94b176d1492508c
MD5 a08b95e1901e8d8b9d69a0b0262c62b4
BLAKE2b-256 8cffaf3a6defbc59db88acbad337d54ce692f7d9bb770c115cafba222b7bb812

See more details on using hashes here.

File details

Details for the file authup-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: authup-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.9.9 Windows/10

File hashes

Hashes for authup-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3cf500d69f71de83a1bbe5a764c46d58b0dd81243880817eae2421db73e835de
MD5 4f807b2ecf324f6657849f7e4d2a1d06
BLAKE2b-256 6e110a4d26500abebb900b1f1c5339d97680a2dc282f1390c00a23cde996666e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page