Imia is an authentication library for Starlette and FastAPI (python 3.8+).

Overview

Imia

Imia (belarussian for "a name") is an authentication library for Starlette and FastAPI (python 3.8+).

PyPI GitHub Workflow Status GitHub Libraries.io dependency status for latest release PyPI - Downloads GitHub Release Date Lines of code

Production status

The library is considered in "beta" state thus may contain bugs or security issues, but I actively use it in production.

Installation

Install imia using PIP or poetry:

pip install imia
# or
poetry add imia

Features

  • Login/logout flows
  • Pluggable authenticators:
    • WWW-Basic
    • session
    • token
    • bearer token
    • any token (customizable)
    • API key
  • Database agnostic user storage
  • Authentication middleware
    • with fallback strategies:
      • redirect to an URL
      • raise an exception
      • do nothing
    • with optional URL protection
    • with option URL exclusion from protection
  • User Impersonation (stateless and stateful)
  • SQLAlchemy 1.4 (async mode) integration

TODO

  • remember me

A very quick start

If you are too lazy to read this doc, take a look into examples/ directory. There you will find several files demoing various parts of this library.

How it works?

Here are all moving parts:

  1. UserLike object, aka "user model" - is an arbitrary class that implements imia.UserLike protocol.
  2. a user provider - an adapter that loads user model (UserLike object) from the storage (a database).
  3. an authenticator - a class that loads user using the user provider from the request (eg. session)
  4. an authentication middleware that accepts an HTTP request and calls authenticators for a user model. The middleware always populates request.auth with UserToken.
  5. user token is a class that holds authentication state

When a HTTP request reaches your application, an imia.AuthenticationMiddleware will start handling it. The middleware iterates over configured authenticators and stops on the first one that returns non-None value. At this point the request is considered authenticated. If no authenticators return user model then the middleware will create anonymous user token. The user token available in request.auth property. Use user_token.is_authenticated token property to make sure that user is authenticated.

User authentication quick start

  1. Create a user model and implement methods defined by imia.UserLike protocol.
  2. Create an instance of imia.UserProvider that corresponds to your user storage. Feel free to create your own.
  3. Setup one or more authenticators and pass them to the middleware
  4. Add imia.AuthenticationMiddleware to your Starlette application

At this point you are done.

Here is a brief example that uses in-memory provider for demo purpose. For production environment you should use database backed providers like SQLAlchemyORMUserProvider or SQLAlchemyCoreUserProvider. Also, for simplicity reason we will not implement login/logout flow and will authenticate requests using API keys.

str: return self.id.split('@')[0].title() def get_id(self) -> str: return self.id def get_hashed_password(self) -> str: return self.password def get_scopes(self) -> list: return self.scopes async def whoami_view(request: Request) -> JSONResponse: return JSONResponse({ 'id': request.auth.user_id, 'name': request.auth.display_name, }) user_provider = InMemoryProvider({ '[email protected]': User(id='[email protected]'), '[email protected]': User(id='[email protected]'), }) authenticators = [ APIKeyAuthenticator(user_provider=user_provider), ] routes = [ Route('/', whoami_view), ] middleware = [ Middleware(AuthenticationMiddleware, authenticators=authenticators) ] app = Starlette(routes=routes, middleware=middleware) ">
from dataclasses import dataclass, field

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

from imia import APIKeyAuthenticator, AuthenticationMiddleware, InMemoryProvider


@dataclass
class User:
    """This is our user model. It may be an ORM model, or any python class, the library does not care of it,
    it only expects that the class has methods defined by the UserLike protocol."""

    id: str
    password: str = 'password'
    scopes: list[str] = field(default_factory=list)

    def get_display_name(self) -> str:
        return self.id.split('@')[0].title()

    def get_id(self) -> str:
        return self.id

    def get_hashed_password(self) -> str:
        return self.password

    def get_scopes(self) -> list:
        return self.scopes


async def whoami_view(request: Request) -> JSONResponse:
    return JSONResponse({
        'id': request.auth.user_id,
        'name': request.auth.display_name,
    })


user_provider = InMemoryProvider({
    '[email protected]': User(id='[email protected]'),
    '[email protected]': User(id='[email protected]'),
})

authenticators = [
    APIKeyAuthenticator(user_provider=user_provider),
]

routes = [
    Route('/', whoami_view),
]

middleware = [
    Middleware(AuthenticationMiddleware, authenticators=authenticators)
]

app = Starlette(routes=routes, middleware=middleware)

Now save the file to myapp.py and run it with uvicorn application server:

uvicorn myapp:app

Open http://127.0.0.1:8000/ and see that your request is not authenticated and user is anonymous. Let's pass API key via query parameters to make the configured APIKeyAuthenticator to load user. This time open http://127.0.0.1:8000/[email protected] in your browser. Now the request is fully authenticated as User1 user.

For more details refer to the doc sections below.

Docs

  1. UserLike protocol (a user model)
  2. Load user from databases using User Providers
  3. Request authentication
  4. Built-in authenticators
  5. User token
  6. Passwords
  7. Login/Logout flow
  8. User impersontation

Usage

See examples/ directory.

You might also like...
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

Two factor authentication system using azure services and python language and its api's
Two factor authentication system using azure services and python language and its api's

FUTURE READY TALENT VIRTUAL INTERSHIP PROJECT PROJECT NAME - TWO FACTOR AUTHENTICATION SYSTEM Resources used: * Azure functions(python)

Toolkit for Pyramid, a Pylons Project, to add Authentication and Authorization using Velruse (OAuth) and/or a local database, CSRF, ReCaptcha, Sessions, Flash messages and I18N

Apex Authentication, Form Library, I18N/L10N, Flash Message Template (not associated with Pyramid, a Pylons project) Uses alchemy Authentication Authe

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes

Flask-HTTPAuth Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation The easiest way to install this is t

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes

Flask-HTTPAuth Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation The easiest way to install this is t

Django Rest Framework App wih JWT Authentication and other DRF stuff

Django Queries App with JWT authentication, Class Based Views, Serializers, Swagger UI, CI/CD and other cool DRF stuff API Documentaion /swagger - Swa

Foundation Auth Proxy is an abstraction on  Foundations' authentication layer and is used to authenticate requests to Atlas's REST API.
Foundation Auth Proxy is an abstraction on Foundations' authentication layer and is used to authenticate requests to Atlas's REST API.

foundations-auth-proxy Setup By default the server runs on http://0.0.0.0:5558. This can be changed via the arguments. Arguments: '-H' or '--host': ho

CheckList-Api - Created with django rest framework and JWT(Json Web Tokens for Authentication)

CheckList Api created with django rest framework and JWT(Json Web Tokens for Aut

Comments
  • Support for installing without SQLAlchemy dependency

    Support for installing without SQLAlchemy dependency

    The package depends on SQLAlchemy 1.4+, but this is only used for specific user providers. I'd like to use it in a project that still needs SQLAlchemy 1.3, and am happy to write my own user providers. It would be great if the default install did not require SQLAlchemy at all, and move this to an extras_require option instead.

    opened by mxsasha 3
  • Added example for database presistence using databases library.

    Added example for database presistence using databases library.

    @alex-oleshkevich I got working one implementation with starlette-databases-imia combination. It is not that neat but is working perfectly.

    Kindly check the issue #4 and thanks for guiding in the right direction.

    opened by jeetu7 3
  • Example for sqlalchemy core.

    Example for sqlalchemy core.

    I am trying to implement basic integration with imia-starlette-databases. The databases is using sqlalchemy-core/aiosqlite in the backend. I am at total loss about how to use imia with sqlite file persistence using the above libs. This might be due to my ignorance of protocols in python or me being new in async world.

    It would be nice if you can have one example in the examples dir with database persistence.

    My current state: login_logout_databases_sqlite

    Thanks in advance

    opened by jeetu7 3
Releases(v0.5.3)
Owner
Alex Oleshkevich
Software Engineer
Alex Oleshkevich
Spotify User Token Generator Template

Spotify User Token Generator Template Quick Start $ pip3 install -r requirements

Arda Soyer 1 Feb 01, 2022
Storefront - A store App developed using Django, RESTFul API, JWT

Storefront A store App developed using Django, RESTFul API, JWT. SQLite has been

Muhammad Algshy 1 Jan 07, 2022
A recipe sharing API built using Django rest framework.

Recipe Sharing API This is the backend API for the recipe sharing platform at https://mesob-recipe.netlify.app/ This API allows users to share recipes

Hannah 21 Dec 30, 2022
Authentication testing framework

What is this This is a framework designed to test authentication for web applications. While web proxies like ZAProxy and Burpsuite allow authenticate

DigeeX 140 Jul 06, 2022
A Login/Registration GUI Application with SQLite database for manipulating data.

Login-Register_Tk A Login/Registration GUI Application with SQLite database for manipulating data. What is this program? This program is a GUI applica

Arsalan 1 Feb 01, 2022
A simple Boilerplate to Setup Authentication using Django-allauth 🚀

A simple Boilerplate to Setup Authentication using Django-allauth, with a custom template for login and registration using django-crispy-forms.

Yasser Tahiri 13 May 13, 2022
A Python library to create and validate authentication tokens

handshake A Python library to create and validate authentication tokens. handshake is used to generate and validate arbitrary authentication tokens th

0 Apr 26, 2022
:couple: Multi-user accounts for Django projects

django-organizations Summary Groups and multi-user account management Author Ben Lopatin (http://benlopatin.com) Status Separate individual user ident

Ben Lopatin 1.1k Jan 09, 2023
Python's simple login system concept - Advanced level

Simple login system with Python - For beginners Creating a simple login system using python for beginners this repository aims to provide a simple ove

Low_Scarlet 1 Dec 13, 2021
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒 Single- and multi-tenant support.

Easy and secure implementation of Azure AD for your FastAPI APIs 🔒 Single- and multi-tenant support.

Intility 220 Jan 05, 2023
Some scripts to utilise device code authorization for phishing.

OAuth Device Code Authorization Phishing Some scripts to utilise device code authorization for phishing. High level overview as per the instructions a

Daniel Underhay 6 Oct 03, 2022
A flask extension for managing permissions and scopes

Flask-Pundit A simple flask extension to organize resource authorization and scoping. This extension is heavily inspired by the ruby Pundit library. I

Anurag Chaudhury 49 Dec 23, 2022
Beihang University Network Authentication Login

北航自动网络认证使用说明 主文件 gw_buaa.py # @file gw_buaa.py # @author Dong # @date 2022-01-25 # @email windcicada 0 Jul 22, 2022

Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.

Flask-User v1.0 Attention: Flask-User v1.0 is a Production/Stable version. The previous version is Flask-User v0.6. User Authentication and Management

Ling Thio 997 Jan 06, 2023
Djagno grpc authentication service with jwt auth

Django gRPC authentication service STEP 1: Install packages pip install -r requirements.txt STEP 2: Make migrations and migrate python manage.py makem

Saeed Hassani Borzadaran 3 May 16, 2022
Simple two factor authemtication system, made by me.

Simple two factor authemtication system, made by me. Honestly, i don't even know How 2FAs work I just used my knowledge and did whatever i could. Send

Refined 5 Jan 04, 2022
This program automatically logs you into a Zoom session at your alloted time

This program automatically logs you into a Zoom session at your alloted time. Optionally you can choose to have end the session at your allotted time.

9 Sep 19, 2022
Authentication with fastapi and jwt cd realistic

Authentication with fastapi and jwt cd realistic Dependencies bcrypt==3.1.7 data

Fredh Macau 1 Jan 04, 2022
Quick and simple security for Flask applications

Note This project is non maintained anymore. Consider the Flask-Security-Too project as an alternative. Flask-Security It quickly adds security featur

Matt Wright 1.6k Dec 19, 2022
Flask JWT Router is a Python library that adds authorised routes to a Flask app.

Read the docs: Flask-JWT-Router Flask JWT Router Flask JWT Router is a Python library that adds authorised routes to a Flask app. Both basic & Google'

Joe Gasewicz 52 Jan 03, 2023