Authentication with Fastapi

Authentication with Fastapi

For our project we need a following packages:

  • pip install pyjwt[crypto] - PyJWT is a library for encoding and decoding JWTs using Python.
  • pip install passlib - Passlib is a library that supports various password hashing algorithms.

FastApi Frameworks provides a lot of Security Tools for implementation of Authentication and Authorization flows. But in this article we will do it by the regular way.

Let's construct the User Model first:

user Model

Also, we provide a schema with nessary fields with pydantic package:

user schema

The post api "/signup" as showen bellow:

HTTP post route for /signup

I would like to create User Service class to take out the business logic from api function:

UserService class

The utils file contain a same functions for password hashing:

utils.py

The generate_password_hash function applied before than plain password will be saved in database.The function generate Password hashing and it's a one-way process of securing plain text password by creating a bit string of a fixed size called hash.

Let's test a SignUp with a request:

signup

So, we got a response body with hashed password that has been saived in Database Table.

response

To exclude the password field from response body we are using exclude option in the Field decorator:

exclude option

Result without password field:

new response body

The login Api:

/login api

In this api function we are check if user is existing if yes we raise the Exception that user already exists, if not we are verify the plain password with the hashed password that situated in database, after that we are creating the both tokens. One it's a access token and another is a refresh token. We will discuss about this tokens after a few moments.

We also using some helpers functions to encode token and to decode token:

encode and decode tokens

Let's test the functionallity:


request for login


response with body

So, we got a response with access and refresh tokens in it. also the id detail of corrensponding user with successful message.

Discussion about tokens

  • Access token allows temporary access to restricted resources such as APIs or websites.?Generally, access tokens are valid for only a few minutes or hours, depending on the setting to safeguard the resource server. They also include security features like signatures.
  • Refresh tokens: A token used to obtain a renewed access token without having to re-authenticate the user. Refresh tokens can last from a few days to a few months.

When we passed a request to login api-point from frontend we get access and refresh token.

the frontend save the tokens on his side.

And with each another request sends the token/'s in request header/cookie.

from fronend to backend request and responce circle

If the access token has been expired the request for refresh token (api/refreshToken) are sent to backend. If refresh token still valid the new Access and Refresh tokens are generated, but if refresh token are also expired the request are rejected and user should to pass Authentication again.

request for renew access and refresh token

The Main problem that how we can to pass a tokens from frontend to backend and vice versa in safe way.

HEADER??? COOKIES??? BODY???


One of the popular ways, it's pass Access token in the header of request.The Authorization header is a part of the HTTP request headers used in client-server communications. Its primary function is to authenticate a user-agent with a server, typically by carrying credentials in the form of a token or a set of credentials like username and password. This header is fundamental in implementing security measures for web applications and APIs.

The Authorization header follows a specific structure:

Authorization: <type> <credentials>        

  • Type: This is the authentication scheme, such as Basic, Bearer, Digest, etc. It indicates the method used for encoding or handling the credentials.
  • Credentials: These are the actual authentication tokens or encoded user credentials. The format and content depend on the authentication scheme.


HTTPS scheme should always be used when using authentication.

I this example i tried to show how we can get the header of request that named "access_token" and sent by frontend. And after that validate the token and bring the existing user from Database.

Get the token from the request header

Let's test it:


test

Cookies:

We added the refresh token to cookies in response by set_cookie method with additional properties.

set_cookie


refresh token as a cookie

In the same way like we did it with Header option we can verify the refresh token and get payload from the token and after that find the user in database.


get user from cookie

User Response

The Code available on github: Auth project: cookies and headers


要查看或添加评论,请登录

David Furman的更多文章

  • FastAPI is the fast way for building APIs?

    FastAPI is the fast way for building APIs?

    "If anyone is looking to build a production Python API, I would highly recommend FastAPI. It is beautifully designed…

  • Easy Backend development with Nest.js (1/5)

    Easy Backend development with Nest.js (1/5)

    Before we begin, ensure you have the following tools and technologies installed on your system: Prerequisites steps:…

  • Fullstack Dockerized Template on Typescript.

    Fullstack Dockerized Template on Typescript.

    We've heard developers voice the same pain points time and again: it's hard to integrate your app's frontend with your…

  • Profile Lookup Application

    Profile Lookup Application

    Welcome to adventures of framework Django that provide all necessary technics and possibilities to develop any kind of…

  • Data Visualization with Matplotlib

    Data Visualization with Matplotlib

    One of the ways to visualize the data the Matplotlib library are used. Let's start our deep journey with Single-Line…

  • Http Authentication and Authorization with Spring Security

    Http Authentication and Authorization with Spring Security

    First of all it's important to understand difference between Authentication and Authorization!By this simple tutorial…

  • Automation Sport News Scrapped and Implemented

    Automation Sport News Scrapped and Implemented

    Tutorial for scrapped content: 1.Now create simple pattern by qt Designer and convert it to python code.

社区洞察

其他会员也浏览了