Tuesday, July 12, 2022

Bearer token authentication in odoo 14

 

In this blog we will explain how to create bearer token authentication in odoo 14 

first we have to know that we have 2 types of authentications in odoo

* Public Authentication 

* User Authentication

but we want to build APIs with the bearer token authentication so 

First : We have to inherit the ir.http model 

Second : create new class function with our authentication name _auth_method_auth_name , just as bellow 

import logging
from odoo.http import request
from odoo.exceptions import AccessDenied
import pprint
from odoo import api, http, models, tools, SUPERUSER_ID, _
from odoo.http import Response

_logger = logging.getLogger(__name__)

class IrHttp(models.AbstractModel):
    _inherit = 'ir.http'

    @classmethod
    def _auth_method_api_token(cls):
        headers = request.httprequest.environ
        api_token = headers.get("HTTP_AUTHORIZATION")
        api_token = str(api_token)
        token = api_token.replace("Bearer ","")
        user_token = token.replace("'","")
        check_user = 0

        if api_token and 'Bearer' in api_token:
            user_ids = request.env['res.users'].sudo().search([])
            for user in user_ids:
                if user_token == user.access_token:
                    check_user = 1
            if check_user != 0:
                return True
            else:
                raise AccessDenied()
        else:
            raise AccessDenied()

In this case we created bearer token authentication with the name api_token 

Third : use the new authentication 

Eg :
@http.route('/api_name, type='http', auth='api_token', methods=['POST'], csrf=False)

 

No comments:

Post a Comment

Odoo Invoice Qr code issues

There are two main issues must of us facing with the QR code in Odoo invoice & these issues are 1/ QR code displayed as broken image w...