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
Official implementation of the AAAI 2022 paper "Learning Token-based Representation for Image Retrieval"

Token: Token-based Representation for Image Retrieval PyTorch training code for Token-based Representation for Image Retrieval. We propose a joint loc

Hui Wu 42 Dec 06, 2022
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
Django Authetication with Twitch.

Django Twitch Auth Dependencies Install requests if not installed pip install requests Installation Install using pip pip install django_twitch_auth A

Leandro Lopes Bueno 1 Jan 02, 2022
Get inside your stronghold and make all your Django views default login_required

Stronghold Get inside your stronghold and make all your Django views default login_required Stronghold is a very small and easy to use django app that

Mike Grouchy 384 Nov 23, 2022
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
API-key based security utilities for FastAPI, focused on simplicity of use

FastAPI simple security API key based security package for FastAPI, focused on simplicity of use: Full functionality out of the box, no configuration

Tolki 154 Jan 03, 2023
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

Tivix 2.4k Jan 03, 2023
Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc.

Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc. just like the Python DBAPI provides an uniform API for database programming in Python.

Garoa Hacker Clube 12 May 22, 2022
it's a Django application to register and authenticate users using phone number.

django-phone-auth It's a Django application to register and authenticate users using phone number. CustomUser model created using AbstractUser class.

MsudD 4 Nov 29, 2022
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Jan 03, 2023
Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack

Microsoft365_devicePhish Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack This is a simple proof-of-concept script that allows an at

Optiv Security 76 Jan 02, 2023
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
A Python package, that allows you to acquire your RecNet authorization bearer token with your account credentials!

RecNet-Login This is a Python package, that allows you to acquire your RecNet bearer token with your account credentials! Installation Done via git: p

Jesse 6 Aug 18, 2022
User Authentication in Flask using Flask-Login

User-Authentication-in-Flask Set up & Installation. 1 .Clone/Fork the git repo and create an environment Windows git clone https://github.com/Dev-Elie

ONDIEK ELIJAH OCHIENG 31 Dec 11, 2022
examify-io is an online examination system that offers automatic grading , exam statistics , proctoring and programming tests , multiple user roles

examify-io is an online examination system that offers automatic grading , exam statistics , proctoring and programming tests , multiple user roles ( Examiner , Supervisor , Student )

Ameer Nasser 4 Oct 28, 2021
Automatizando a criação de DAGs usando Jinja e YAML

Automatizando a criação de DAGs no Airflow usando Jinja e YAML Arquitetura do Repo: Pastas por contexto de negócio (ex: Marketing, Analytics, HR, etc)

Arthur Henrique Dell' Antonia 5 Oct 19, 2021
Authentication, JWT, and permission scoping for Sanic

Sanic JWT Sanic JWT adds authentication protection and endpoints to Sanic. It is both easy to get up and running, and extensible for the developer. It

Adam Hopkins 229 Jan 05, 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
FastAPI-Login tries to provide similar functionality as Flask-Login does.

FastAPI-Login FastAPI-Login tries to provide similar functionality as Flask-Login does. Installation $ pip install fastapi-login Usage To begin we hav

417 Jan 07, 2023
Library - Recent and favorite documents

Thingy Thingy is used to quickly access recent and favorite documents. It's an XApp so it can work in any distribution and many desktop environments (

Linux Mint 23 Sep 11, 2022