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
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 1, 2023
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 3, 2023
Implements authentication and authorization as FastAPI dependencies

FastAPI Security Implements authentication and authorization as dependencies in FastAPI. Features Authentication via JWT-based OAuth 2 access tokens a

Jacob Magnusson 111 Jan 7, 2023
Authentication with fastapi and jwt cd realistic

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

Fredh Macau 1 Jan 4, 2022
Simple implementation of authentication in projects using FastAPI

Fast Auth Facilita implementação de um sistema de autenticação básico e uso de uma sessão de banco de dados em projetos com tFastAPi. Instalação e con

null 3 Jan 8, 2022
Auth-Starters - Different APIs using Django & Flask & FastAPI to see Authentication Service how its work

Auth-Starters Different APIs using Django & Flask & FastAPI to see Authentication Service how its work, and how to use it. This Repository based on my

Yasser Tahiri 7 Apr 22, 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
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

null 0 Apr 26, 2022
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

null 1k Dec 28, 2022
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

null 962 Feb 4, 2021