Simple implementation of authentication in projects using FastAPI

Overview

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 configuração

Instale usando pip ou seu o gerenciador de ambiente da sua preferencia:

pip install fast-auth

As configurações desta lib são feitas a partir de variáveis de ambiente. Para facilitar a leitura dessas informações o fast_auth procura no diretório inicial(pasta onde o uvicorn ou gunicorn é chamado iniciando o serviço web) o arquivo .env e faz a leitura dele.

Abaixo temos todas as variáveis de ambiente necessárias e em seguida a explição de cada uma:

CONNECTION_STRING=postgresql+asyncpg://postgres:[email protected]:5432/fastapi

SECRET_KEY=1155072ced40aeb1865533335aaec0d88bbc47a996cafb8014336bdd2e719376

TTL_JWT=60

  • CONNECTION_STRING: Necessário para a conexão com o banco de dados. Gerealmente seguem o formato dialect+driver://username:[email protected]:port/database. O driver deve ser um que suporte execuções assíncronas como asyncpg para PostgreSQL, asyncmy para MySQL, para o SQLite o fast_auth já trás o aiosqlite.

  • SECRET_KEY: Para gerar e decodificar o token JWT é preciso ter uma chave secreta, que como o nome diz não deve ser pública. Para gerar essa chave pode ser utilizado o seguinte comando:

    openssl rand -hex 32

  • TTL_JWT: O token JWT deve ter um tempo de vida o qual é especificado por essa variável. Este deve ser um valor inteiro que ira representar o tempo de vida dos token em minutos. Caso não seja definido será utilizado o valor 1440 o equivalente a 24 horas.

Primeiros passos

Após a instalação e especificação da CONNECTION_STRING as tabelas podem ser criada no banco de dados utilizando o seguinte comando no terminal:

migrate

Este comando irá criar 3 tabelas, auth_users, auth_groups e auth_users_groups. Tendo criado as tabelas, já será possível criar usuários pela linha de comando:

create_user

Ao executar o comando será solicitado o username e password.

Como utilizar

Toda a forma de uso foi construida seguindo o que consta na documentação do FastAPI

Conexao com banco de dados

Tendo a CONNECTION_STRING devidamente especificada, para ter acesso a uma sessão do banco de dados a partir de uma path operation basta seguir o exemplo abaixo:

from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from fast_auth import connection_database, get_db

connection_database()

app = FastAPI()


@app.get('/get_users')
async def get_users(db: AsyncSession = Depends(get_db)):
    result = await db.execute('select * from auth_users')
    return [dict(user) for user in result]

Explicando o que foi feito acima, a função connection_database estabelece conexão com o banco de dados passando a CONNECTION_STRING para o SQLAlchemy, mais especificamente para a função create_async_engine. No path operation passamos a função get_db como dependencia, sendo ele um generator que retorna uma sessão assincrona já instanciada, basta utilizar conforme necessário e o fast_auth mais o prório fastapi ficam responsáveis por encerrar a sessão depois que a requisição é retornada.

Autenticação - Efetuando login

Abaixo um exemplo de rota para authenticação:

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from fast_auth import connection_database, authenticate, create_token_jwt

connection_database()

app = FastAPI()


class SchemaLogin(BaseModel):
    username: str
    password: str


@app.post('/login'):
async def login(credentials: SchemaLogin):
    user = await authenticate(credentials.username, credentials.password)
    if user:
        token = create_token_jwt(user)
        return {'access': token}

A função authenticate é responsável por buscar no banco de dados o usuário informado e checar se a senha confere, se estiver correto o usuário(objeto do tipo User que está em fast_auth.models) é retornado o qual deve ser passado como parâmetro para a função create_token_jwt que gera e retorna o token. No token fica salvo por padrão o id e o username do usuário, caso necessário, pode ser passado um dict como parametro com informações adicionais para serem empacotadas junto.

Autenticação - requisição autenticada

O exemplo a seguir demonstra uma rota que só pode ser acessada por um usuário autenticado:

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from fast_auth import connection_database, require_auth

connection_database()

app = FastAPI()


@app.get('/authenticated')
def authenticated(payload: dict = Depends(require_auth)):
    #faz alguma coisa
    return {}

Para garantir que uma path operation seja executada apenas por usuários autenticados basta importar e passar ccomo dependência a função require_auth. Ela irá retornar os dados que foram empacotados no token JWT.

Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster

Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster. Kubernetes supports OpenID Connect Tokens as a way to identify users wh

7 Nov 20, 2022
A simple model based API maker written in Python and based on Django and Django REST Framework

Fast DRF Fast DRF is a small library for making API faster with Django and Django REST Framework. It's easy and configurable. Full Documentation here

Mohammad Ashraful Islam 18 Oct 05, 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
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

Miguel Grinberg 1.1k Jan 05, 2023
Django Admin Two-Factor Authentication, allows you to login django admin with google authenticator.

Django Admin Two-Factor Authentication Django Admin Two-Factor Authentication, allows you to login django admin with google authenticator. Why Django

Iman Karimi 9 Dec 07, 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

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

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
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
Authware API wrapper for Python 3.5+

AuthwarePy Asynchronous wrapper for Authware in Python 3.5+ View our documentation 📲 Installation Run this to install the library via pip: pip instal

Authware 3 Feb 09, 2022
Script that provides your TESLA access_token and refresh_token

TESLA tokens This script helps you get your TESLA access_token and refresh_token in order to connect to third party applications (Teslamate, TeslaFi,

Bun-Ny TAN 3 Apr 28, 2022
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

shantanu nimkar 1 Jan 24, 2022
Login-python - Login system made in Python, using native libraries

login-python Sistema de login feito 100% em Python, utilizando bibliotecas nativ

Nicholas Gabriel De Matos Leal 2 Jan 28, 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
Imia is an authentication library for Starlette and FastAPI (python 3.8+).

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

Alex Oleshkevich 91 Nov 24, 2022
Django-registration (redux) provides user registration functionality for Django websites.

Description: Django-registration provides user registration functionality for Django websites. maintainers: Macropin, DiCato, and joshblum contributor

Andrew Cutler 920 Jan 08, 2023
JSON Web Token implementation in Python

PyJWT A Python implementation of RFC 7519. Original implementation was written by @progrium. Sponsor If you want to quickly add secure token-based aut

José Padilla 4.5k Jan 09, 2023
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://frankie567.github.io/fastapi-users/ Source Code: https

François Voron 2.4k Jan 04, 2023
Use this to create (admin) personal access token in gitlab database. Mainly used for automation.

gitlab-personal-access-token Ensure PAT is present in gitlab database. This tool is mainly used when you need to automate gitlab installation and conf

CINAQ Internet Technologies 1 Jan 30, 2022
Plotly Dash plugin to allow authentication through 3rd party OAuth providers.

dash-auth-external Integrate your dashboards with 3rd parties and external OAuth providers. Overview Do you want to build a Plotly Dash app which pull

James Holcombe 15 Dec 11, 2022