Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Accounting
  • Inventory
  • PoS
  • Project
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

How to create a custom controller with user authentication - Odoo13?

Subscribe

Get notified when there's activity on this post

This question has been flagged
authenticationusercontrollers
8 Replies
26056 Views
Avatar
Kabeer KB

I am trying to create a custom controller with user authentication.
Here is what i did.

        class GetUserDetails(http.Controller):
        @http.route('/web/getUserDetail',auth='user',type='json')
        def getChit(self,**kw):
            print('Inside getUser detail',kw)

Issue 1: When i call this controller from an API client (ARC) its directly get into that function, without any authentication.???

Issue 2: If we solved the above issue, how can i authenticate a user via API call/client.

Actually i want to get user details in android app.

1
Avatar
Discard
Avatar
Yenthe Van Ginneken (Mainframe Monkey)
Best Answer

Hi,

If you want to call a controller with auth='user' you should first get your user id and session_id and then continue from there. You can get the session_details from /web/session/authenticate like this:

session_details = requests.get(url=odoo_url + '/web/session/authenticate', data=json.dumps(data_string), headers=headers)
session_id = str(session_details.cookies.get('session_id'))

Once you have the session details you can set your cookies/values and call the endpoint:

cookies = {
'username': db_username,
'password': db_password,
'session_id': session_id // which we just got in the previous code block
}
requests.get(url=odoo_url + '/web/getUserDetail', params=params, headers=headers, cookies=cookies)

Regards,
Yenthe

1
Avatar
Discard
Kabeer KB
Author

@ Yenthe, i got the session id and i tried to call the url as per your solution but getting this error `Function declared as capable of handling request of type 'json' but called with a request of type 'http'`.

Yenthe Van Ginneken (Mainframe Monkey)

That happens when you call the controller with the wrong type or data. Make sure you're doing a get request which has the parameters, headers and cookies and that it contains JSON.

SOUJIRO30

Is it available in Odoo 14?

Osama Hassan

we need to reassign user and pass in cookies as well ?? if we authenticate

Avatar
TravisScott
Best Answer

To create a custom controller with user authentication in Odoo 13, define your controller class using @http.route and implement the @http.auth decorator for user access. Ensure to handle session management and access rights in your methods accordingly.

0
Avatar
Discard
Avatar
Vasiliy "hoshiyoumu" Kuznetsov
Best Answer

As I was searching for Odoo user authentication via Postman and this thread was the best matching result I want to share resulting minimal example

Hopes it will help somebody

Environment: containerized Odoo17

import yaml

from odoo import http, Command
from odoo.http import request

class ExampleController(http.Controller):
@http.route('/api/v1/example/', type='json', auth='user', methods=['POST'], csrf=True)
def create_example(self):
kwargs = yaml.load(request.httprequest.data) # incoming json data
resp = some_internal_function(kwargs)
return resp


Authentication request in postman

http://127.0.0.1:8069/web/session/authenticate

Headers: Content-Type: application/json Body: (raw/JSON)

{
"params": {
"db": "my_odoo_dbname",
"login": "user",
"password": "their_password"
}
}

If succeed, in response there will be Cookies section. <>
Copy session_id​ key


Authenticated request in postman

http://127.0.0.1:8069/api/v1/example/

Headers: Content-Type: application/json/
Cookie: session_id=YOURSESSIONID Body: (raw/JSON)
YOUR JSON BODY
0
Avatar
Discard
Avatar
ChunYi Fu
Best Answer

I have the same problem now, looks like odoo removed session concept since some release.  So the web client session never expires, and there is no session in json-rpc interface at all, only user id is used there.  Did you guys use session id finally?

0
Avatar
Discard
Avatar
Alan Luo
Best Answer

default on odoo 13 there is no session_id response, but you can add it manual by add:

it from addons: 'Auth Session Info' by Hariprasath.B

# -*- coding: utf-8 -*-

from odoo import models
from odoo.http import request


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

def session_info(self):
res = super(Http, self).session_info()
if not res.get('session_id'):
# Add Session Id
res['session_id'] = request.session.sid
return res
0
Avatar
Discard
Avatar
Anand Raja K
Best Answer

@Niyas , the response is as you got. But if you try session_details.cookies.get('session_id') will get session_id definitely.

0
Avatar
Discard
Avatar
it@mycb1.com
Best Answer

In Odoo 13 the session_id is in cookies

0
Avatar
Discard
Avatar
Niyas Raphy (Walnut Software Solutions)
Best Answer

Hi,

As the auth='user' is given,  the route the controller will be accessible only for the authenticated users, else it will show some invalid or session_expired response .


Issue 1: I have checked some custom functions using the postman application and it seems working fine with auth='user' , if there is no valid session_id it will ask to authenticate first. In your case can you try the same with the postman application and confirm.

Issue 2: For authentication use the controller, /web/session/authenticate .


See the detailed Video Here: Authentication, Fetching Data & Creating Records Using Controller


Thanks

0
Avatar
Discard
Kabeer KB
Author

@Niyas, Thanks for the answer.

I tried to gt session by calling `http://localhost:5013/web/session/authenticate`. in the response, i couldn't find `sessino_id`.

here is the output.

{

"jsonrpc": "2.0",

"id": null,

"result": {

"uid": 2,

"is_system": true,

"is_admin": true,

"user_context": {

"lang": "en_US",

"tz": false,

"uid": 2

},

"db": "demo_odoo13",

"server_version": "13.0-20191007",

"server_version_info": [

13,

0,

0,

"final",

0,

""

],

"name": "Administrator",

"username": "admin",

"partner_display_name": "Administrator",

"company_id": 1,

"partner_id": 3,

"user_companies": {

"current_company": [

1,

"My Company"

],

"allowed_companies": [

[

1,

"My Company"

]

]

},

"currencies": {

"1": {

"symbol": "€",

"position": "after",

"digits": [

69,

2

]

},

"2": {

"symbol": "$",

"position": "before",

"digits": [

69,

2

]

}

},

"web.base.url": "http://localhost:5013",

"show_effect": "True",

"display_switch_company_menu": false,

"cache_hashes": {

"load_menus": "b7ea4d99293455ecb82c8d87efd5653792dc22b7",

"qweb": "befe30ca4d3deb2880b68d2532163699398dba61",

"translations": "026ae15487c2067877f7b82ffb991974c070d399"

},

"web_tours": [],

"out_of_office_message": false,

"odoobot_initialized": true

}

}

Kabeer KB
Author

@ Niyas, I tried with post man, but the same result, i can access it without session_id. When i print `request.env.user.name` it Prints `Administrator`.

Prakash

@Niyas I have query related to api posted in the odoo forum please check this link https://www.odoo.com/forum/help-1/api-get-model-data-with-particular-user-only-190580

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Sign up
Related Posts Replies Views Activity
How to connect a users instead of login process? Solved
authentication user
Avatar
Avatar
1
Sep 21
2696
Custom controller route with no authentication Solved
authentication controllers odoo10.0
Avatar
Avatar
4
Jan 19
3901
Custom authentication, javascript never call
javascript authentication controllers contro
Avatar
1
May 17
5702
Form to authenticate new users (Login)
authentication form user login
Avatar
0
Oct 16
4497
Where is logged the default template user in python code?
authentication user template signup
Avatar
Avatar
1
Aug 15
7600
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now