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.

Implementation of Supervised Contrastive Learning with AMP, EMA, SWA, and many other tricks

SupCon-Framework The repo is an implementation of Supervised Contrastive Learning. It's based on another implementation, but with several differencies

Ivan Panshin 132 Dec 14, 2022
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
AddressBookApp - Address Book App in Django

AddressBookApp Application Name Address Book App in Django, 2022 Technologies La

Joshua K 1 Aug 18, 2022
Simple Login - Login Extension for Flask - maintainer @cuducos

Login Extension for Flask The simplest way to add login to flask! How it works First, install it from PyPI: $ pip install flask_simplelogin Then, use

Flask Extensions 181 Jan 01, 2023
Ready to use and customizable Authentications and Authorisation management for FastAPI ⚡

AuthenticationX 💫 Ready-to-use and customizable Authentications and Oauth2 management for FastAPI ⚡

Yasser Tahiri 408 Jan 05, 2023
Flask Implementation of a login page and some basic functionality.

login_page Flask Implementation of a login page and some basic functionality. How to Run $ chmod +x run.sh setup.sh $ # run setup.sh only if the datab

3 Jun 03, 2021
OpenStack Keystone auth plugin for HTTPie

httpie-keystone-auth OpenStack Keystone auth plugin for HTTPie. Installation $ pip install --upgrade httpie-keystone-auth You should now see keystone

Pavlo Shchelokovskyy 1 Oct 20, 2021
OAuth2 goodies for the Djangonauts!

Django OAuth Toolkit OAuth2 goodies for the Djangonauts! If you are facing one or more of the following: Your Django app exposes a web API you want to

Jazzband 2.7k Jan 01, 2023
An open source Flask extension that provides JWT support (with batteries included)!

Flask-JWT-Extended Features Flask-JWT-Extended not only adds support for using JSON Web Tokens (JWT) to Flask for protecting views, but also many help

Landon Gilbert-Bland 1.4k Jan 04, 2023
Mock authentication API that acceccpts email and password and returns authentication result.

Mock authentication API that acceccpts email and password and returns authentication result.

Herman Shpryhau 1 Feb 11, 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
python implementation of JSON Web Signatures

python-jws 🚨 This is Unmaintained 🚨 This library is unmaintained and you should probably use For histo

Brian J Brennan 57 Apr 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
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
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
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

Dessa - Open Source 2 Jul 03, 2020
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
Login qr line & qr image

login-qr-line-qr-image login qr line & qr image python3 & linux ubuntu api source: https://github.com/hert0t/BEAPI-BETA import httpx import qrcode fro

Alif Budiman 1 Dec 27, 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