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.

Local server that gives you your OAuth 2.0 tokens needed to interact with the Conta Azul's API

What's this? This is a django project meant to be run locally that gives you your OAuth 2.0 tokens needed to interact with Conta Azul's API Prerequisi

Fábio David Freitas 3 Apr 13, 2022
A recipe sharing API built using Django rest framework.

Recipe Sharing API This is the backend API for the recipe sharing platform at https://mesob-recipe.netlify.app/ This API allows users to share recipes

Hannah 21 Dec 30, 2022
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
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
Google Auth Python Library

Google Auth Python Library This library simplifies using Google's various server-to-server authentication mechanisms to access Google APIs. Installing

Google APIs 598 Jan 07, 2023
Web authentication testing framework

What is this This is a framework designed to test authentication for web applications. While web proxies like ZAProxy and Burpsuite allow authenticate

OWASP 88 Jan 01, 2023
Generate payloads that force authentication against an attacker machine

Hashgrab Generates scf, url & lnk payloads to put onto a smb share. These force authentication to an attacker machine in order to grab hashes (for exa

xct 35 Dec 20, 2022
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
Todo app with authentication system.

todo list web app with authentication system. User can register, login, logout. User can login and create, delete, update task Home Page here you will

Anurag verma 3 Aug 18, 2022
This is a Python library for accessing resources protected by OAuth 2.0.

This is a client library for accessing resources protected by OAuth 2.0. Note: oauth2client is now deprecated. No more features will be added to the l

Google APIs 787 Dec 13, 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
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
Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.

Flask-User v1.0 Attention: Flask-User v1.0 is a Production/Stable version. The previous version is Flask-User v0.6. User Authentication and Management

Ling Thio 997 Jan 06, 2023
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
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
This is a Token tool that gives you many options to harm the account.

Trabis-Token-Tool This is a Token tool that gives you many options to harm the account. Utilities With this tools you can do things as : ·Delete all t

Steven 2 Feb 13, 2022
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
Python library for generating a Mastercard API compliant OAuth signature.

oauth1-signer-python Table of Contents Overview Compatibility References Usage Prerequisites Adding the Library to Your Project Importing the Code Loa

23 Aug 01, 2022
Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication.

auth-phyton Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication. Setup Step #1 - Install dependencies $ pip

sandhika 0 Aug 03, 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