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.

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

95 Nov 28, 2022
OpenConnect auth creditials collector.

OCSERV AUTH CREDS COLLECTOR V1.0 Зачем Изначально было написано чтобы мониторить какие данные вводятся в интерфейс ханипота в виде OpenConnect server.

0 Sep 23, 2022
row level security for FastAPI framework

Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

Holger Frey 315 Dec 25, 2022
This script helps you log in to your LMS account and enter the currently running session

This script helps you log in to your LMS account and enter the currently running session, all in a second

Ali Ebrahimi 5 Sep 01, 2022
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
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
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
Graphical Password Authentication System.

Graphical Password Authentication System. This is used to increase the protection/security of a website. Our system is divided into further 4 layers of protection. Each layer is totally different and

Hassan Shahzad 12 Dec 16, 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
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
RSA Cryptography Authentication Proof-of-Concept

RSA Cryptography Authentication Proof-of-Concept This project was a request by Structured Programming lectures in Computer Science college. It runs wi

Dennys Marcos 1 Jan 22, 2022
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)

BHUSHAN SATISH DESHMUKH 1 Dec 10, 2021
Flask user session management.

Flask-Login Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users

Max Countryman 3.2k Dec 28, 2022
Brute force a JWT token. Script uses multithreading.

JWT BF Brute force a JWT token. Script uses multithreading. Tested on Kali Linux v2021.4 (64-bit). Made for educational purposes. I hope it will help!

Ivan Šincek 5 Dec 02, 2022
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 07, 2023
Basic auth for Django.

Basic auth for Django.

bichanna 2 Mar 25, 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
FastAPI Simple authentication & Login API using GraphQL and JWT

JeffQL A Simple FastAPI authentication & Login API using GraphQL and JWT. I choose this Name JeffQL cause i have a Low level Friend with a Nickname Je

Yasser Tahiri 26 Nov 24, 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
JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction

JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction This script performs a Java Web Token Key Confusion

Alex Fronteddu 1 Jan 13, 2022