Enable Dark Mode!
By: Risvana AR

FastAPI Session Based Authentication in Odoo 15 ERP

Technical Odoo 15

FastAPI is a web framework. It is used in Python libraries. The framework provides powerful authentication and provides security. It is used for automatic validation and conversion to the valid data request type. It handles common user errors and does so in inline code. Odoo translation is very easy with the Fast API. Creating an environment of objects is easy and can interact with libraries and registries.
We can use different methods to manage security, authentication, and authorization. Many frameworks handle security and authentication. FastAPI provides several tools to help you manage security easily. OAuth2 handles authentication and authorization. It is a very broad specification and covers many complex use cases. This includes ways to authenticate with a "third party." We have two types of authentication OAuth1 and 2. Authentication differs in 2 cases, OAuth 1, which is much different and more complex than OAuth2, because it involves direct specifications on how to encrypt communication. The encryption of the particular authentication does not get in the OAuth token. So, encrypted communication gives better functionality.
Security Schema:
apiKey: an application-specific key that can come from:
A query parameter.
A cookie.
A header.
http: standard HTTP authentication systems, includes
Bearer: This is inherited from OAuth2. Create a header, and that can be authorized the predominant token
Basic Authentication
Authentication provider
openIdConnect : discover OAuth2 Authentication
If you have a backend and frontend domain and different paths of the same domain and want to authenticate with the backend with a username and password then in that case you can use OAuth2 to do it using FastAPI
Create main.py
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}
Run the example with:
$ uvicorn main:app --reload
a) Type the username and password in the front end and press enter. The front end sends the specific username and password, which will be routed to the corresponding URL in our API.
b) The API verifies the username and password and sends the generated token request.    
c) The front end provides an option to click, and it will go through another section of the web. After triggering that verify the corresponding token.
Get current user
async def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}
Create a User model
First, we can create a pydantic user model, in the same method we can create the pydantic body.
from typing import Union
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
    username: str
    email: Union[str, None] = None
    full_name: Union[str, None] = None
    disabled: Union[bool, None] = None
Create a get current user
get_current_user  they have dependency with the OAuth token
async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)
    return user
Get the user
get_current_user will use a function that generate the  token as a str and it returns the Pydantic User model:
def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)
    return user
Inject the current user
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user
In the case of Fast API that connects with Odoo we can use the endpoint in the session to create the particular Authentication.define the token with username and password and used an environment that depends on the Odoo.
async def token(username: str, password: str, env: Environment = Depends(odoo_env)):
   u_id = env['res.users'].authenticate(env['res.users'], username,
                                        password, '')
   if not u_id:
       return {"Status": "Error", "Message": "Incorrect username or password"}
   assert password
       "SELECT COALESCE(password, '') FROM res_users WHERE id=%s" % u_id
   [hashed] = env.cr.fetchone()
   valid, replacement = passlib.context.CryptContext(
       ['pbkdf2_sha512', 'plaintext'],
   ) \
       .verify_and_update(password, hashed)
   if not valid:
       return {"Status": "Error", "Message": "Incorrect username or password"}
   if valid:
       api_authentication_token = env['res.users'].browse(u_id)
       return {"status": "success",
               "Auth_token": api_authentication_token.id
PassLib is a great Python package. It is used to handle password hashes. CryptContext is used for hashing passwords that are used in the algorithms.
That’s all about the Fast API Session-based Authentication SetUp in Odo. It is the method for creating Authentication using FastAPI sessions. We can set up the authentication with the OAuth token. It covered the process of securing FastAPI with tokens.

If you need any assistance in odoo, we are online, please chat with us.


Leave a comment




Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635



Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.



Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message