Skip to main content

Python plugins for the Authup authentication and authorization framework

Project description

CI codecov PyPI - Python Version PyPI - Downloads Maintainability 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]

Table of Contents

Installation

The plugins are available via PyPi.

pip install authup-py

Extra dependencies

The plugin for the project's base library httpx needs 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 AuthupUser
from authup import User
from authup.permissions import Permission

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

required_permissions = AuthupUser(
    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

poetry run 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.5.0.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

authup-0.5.0-py3-none-any.whl (22.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: authup-0.5.0.tar.gz
  • Upload date:
  • Size: 16.0 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.5.0.tar.gz
Algorithm Hash digest
SHA256 16b550ff4324ff44c7f78134361a2ed891ef677669ece6be2efaea4ac920734d
MD5 215055e1ab83326bc047e631c50fbfb8
BLAKE2b-256 c0b5f0afd88a9234c2f5674dde12e1c5b1c2f5707cbecb41bdc2f3d92f3141e5

See more details on using hashes here.

File details

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

File metadata

  • Download URL: authup-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 22.7 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.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e581d62ca5a02624f12de1e7d0b8feecebf74757f5e9658a6ca1f24b13118199
MD5 8ff8eaed561f67dccae77099011557d5
BLAKE2b-256 c79855f26aa7b4f9a0bc7af883f5f6a40a1446f876e92ca56eafafb7432ef1d0

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