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.

A wagtail plugin to replace the login by an OAuth2.0 Authorization Server

Wagtail OAuth2.0 Login Plugin to replace Wagtail default login by an OAuth2.0 Authorization Server. What is wagtail-oauth2 OAuth2.0 is an authorizatio

Gandi 7 Oct 07, 2022
Python module for generating and verifying JSON Web Tokens

python-jwt Module for generating and verifying JSON Web Tokens. Note: From version 2.0.1 the namespace has changed from jwt to python_jwt, in order to

David Halls 210 Dec 24, 2022
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 02, 2023
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
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 JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 28, 2022
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
python-social-auth and oauth2 support for django-rest-framework

Django REST Framework Social OAuth2 This module provides OAuth2 social authentication support for applications in Django REST Framework. The aim of th

1k Dec 22, 2022
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
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
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
PetitPotam - Coerce NTLM authentication from Windows hosts

Python implementation for PetitPotam

ollypwn 137 Dec 28, 2022
API with high performance to create a simple blog and Auth using OAuth2 ⛏

DogeAPI API with high performance built with FastAPI & SQLAlchemy, help to improve connection with your Backend Side to create a simple blog and Cruds

Yasser Tahiri 111 Jan 05, 2023
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
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
🔐 Login & Register System

🔐 Login & Register System This is a developable login and register system. Enter your username and password to register or login to account. Automati

Firdevs Akbayır 10 Dec 12, 2022
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
Simplifying third-party authentication for web applications.

Velruse is a set of authentication routines that provide a unified way to have a website user authenticate to a variety of different identity provider

Ben Bangert 253 Nov 14, 2022
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

Rafael Salimov 4 Jan 29, 2022
Per object permissions for Django

django-guardian django-guardian is an implementation of per object permissions [1] on top of Django's authorization backend Documentation Online docum

3.3k Jan 01, 2023