Welcome to Tesla Motors Club
Discuss Tesla's Model S, Model 3, Model X, Model Y, Cybertruck, Roadster and More.
Register

Generate V3 Refresh Token for API Authentication using Python

This site may earn commission on affiliate links.
There is already a nice little method on here using PHP created by MrTemple. I saw a few comments from people struggling to get it configured so I figured I'd document a simple step-by-step method using Python as an alternative.


*NOTE: This guide assumes Python is not already installed and Windows is your operating system. (These steps can be easily adjusted/followed on Linux and MacOS.)


PREREQUISITES:


STEPS:

  1. Download the prerequisites
  2. Create a project folder to store your files; e.g., “C:\Users\Username\Desktop\TeslaTokens”
  3. Place: ChromeDriver, auth.tokens.py, and requirements.txt in “C:\Users\Username\Desktop\TeslaTokens”
  4. Install Python FOR ALL USERS and add to PATH (If you need help installing Python there are plenty of great videos out there explaining the process for each system)
  5. Launch a command window/terminal (e.g., PowerShell, Command Prompt, Terminal, etc.)
  6. Type:
    Code:
    CD C:\Users\Username\Desktop\TeslaTokens
  7. Press: ENTER
  8. Type:
    Code:
    pip install -r requirements.txt
  9. Press: ENTER
  10. At this point everything should be installed, configured and ready to go
  11. Then enter one of the below strings at the command prompt and hit ENTER:

If your Tesla account has MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password' -c 'passcode'

If your Tesla account does not have MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password'

-u = Tesla account email
-p = Tesla account password
-c = Passcode generated by your authenticator app

MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword -c 123456

Non-MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword

TIPS:

  • If python3 does not work try using just python
  • To check your Python install you can type:
    Code:
    python --version
 
There is already a nice little method on here using PHP created by MrTemple. I saw a few comments from people struggling to get it configured so I figured I'd document a simple step-by-step method using Python as an alternative.


*NOTE: This guide assumes Python is not already installed and Windows is your operating system. (These steps can be easily adjusted/followed on Linux and MacOS.)


PREREQUISITES:


STEPS:

  1. Download the prerequisites
  2. Create a project folder to store your files; e.g., “C:\Users\Username\Desktop\TeslaTokens”
  3. Place: ChromeDriver, auth.tokens.py, and requirements.txt in “C:\Users\Username\Desktop\TeslaTokens”
  4. Install Python FOR ALL USERS and add to PATH (If you need help installing Python there are plenty of great videos out there explaining the process for each system)
  5. Launch a command window/terminal (e.g., PowerShell, Command Prompt, Terminal, etc.)
  6. Type:
    Code:
    CD C:\Users\Username\Desktop\TeslaTokens
  7. Press: ENTER
  8. Type:
    Code:
    pip install -r requirements.txt
  9. Press: ENTER
  10. At this point everything should be installed, configured and ready to go
  11. Then enter one of the below strings at the command prompt and hit ENTER:

If your Tesla account has MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password' -c 'passcode'

If your Tesla account does not have MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password'

-u = Tesla account email
-p = Tesla account password
-c = Passcode generated by your authenticator app

MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword -c 123456

Non-MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword

TIPS:

  • If python3 does not work try using just python
  • To check your Python install you can type:
    Code:
    python --version
Thanks for this. I used this a little over one month ago successfully. Unfortuntaely, it's not working today. I'm getting this error:

DevTools listening on ws://127.0.0.1:63948/devtools/browser/xxxx
Traceback (most recent call last):
File "C:\xxx\tesla_tokenV3.py", line 267, in <module>
login(args)
File "C:\xxx\tesla_tokenV3.py", line 77, in login
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name=identity]")))
File "C:\xxx\Python39\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Anyone else that is using this seeing this too?
 
Thanks for this. I used this a little over one month ago successfully. Unfortuntaely, it's not working today. I'm getting this error:

DevTools listening on ws://127.0.0.1:63948/devtools/browser/xxxx
Traceback (most recent call last):
File "C:\xxx\tesla_tokenV3.py", line 267, in <module>
login(args)
File "C:\xxx\tesla_tokenV3.py", line 77, in login
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name=identity]")))
File "C:\xxx\Python39\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Anyone else that is using this seeing this too?
Hey insane,

I just ran it and it worked fine for me. The errors your getting are related to Selenium (ChromeDriver) do you still have ChromeDriver in the same directory with the Python script?
 
Hey insane,

I just ran it and it worked fine for me. The errors your getting are related to Selenium (ChromeDriver) do you still have ChromeDriver in the same directory with the Python script?
I do. I also double-checked that it was the right version in case my Chrome had updated. Very strange! I'll re-boot the server and try from scratch again...Thanks for the reply.

EDIT:
Re-boot no help. I believe the line "DevTools listening on ws://127.0.0.1....." shows that the ChromeDriver is present and being used. My Chrome browser did upgrade from 89.xxx to 90.xxx and I've replaced the ChromeDriver with the correct one, but that didn't change the behavior. Any ideas welcome.
 
Last edited:
Hey insane,

I just ran it and it worked fine for me. The errors your getting are related to Selenium (ChromeDriver) do you still have ChromeDriver in the same directory with the Python script?

I found the fix....
This may very well impact anyone else running this script.. If Chrome updates, it may break things for you. I had to update the USER_AGENT string in the .py script to reflect my NEW version of Chrome. Depending on which version of this code you're using, find either USER_AGENT or UA. Mine was USER_AGENT on line 26.

Original:
USER_AGENT = "Mozilla/5.0 (Linux; Android 10; Pixel 3 Build/QQ2A.200305.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/85.0.4183.81 Mobile Safari/537.36"

But now reads:
USER_AGENT = "Mozilla/5.0 (Linux; Android 10; Pixel 3 Build/QQ2A.200305.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.93 Mobile Safari/537.36"

Interestingly enough, when I first successfully used this script, I was using Chrome v89, but it was ok with the 85 in the code. Not anymore. Updating the User Agent string was the fix for me...hope this helps someone else!

Thanks again @CarvedArt for summarizing and sharing your approach!
 
  • Like
Reactions: tjbonzo
I found the fix....
This may very well impact anyone else running this script.. If Chrome updates, it may break things for you. I had to update the USER_AGENT string in the .py script to reflect my NEW version of Chrome. Depending on which version of this code you're using, find either USER_AGENT or UA. Mine was USER_AGENT on line 26.

Original:
USER_AGENT = "Mozilla/5.0 (Linux; Android 10; Pixel 3 Build/QQ2A.200305.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/85.0.4183.81 Mobile Safari/537.36"

But now reads:
USER_AGENT = "Mozilla/5.0 (Linux; Android 10; Pixel 3 Build/QQ2A.200305.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.93 Mobile Safari/537.36"

Interestingly enough, when I first successfully used this script, I was using Chrome v89, but it was ok with the 85 in the code. Not anymore. Updating the User Agent string was the fix for me...hope this helps someone else!

Thanks again @CarvedArt for summarizing and sharing your approach!
Hey, sorry I didn't receive a notification for your edit, but glad to see you got it sorted out!
 
There is already a nice little method on here using PHP created by MrTemple. I saw a few comments from people struggling to get it configured so I figured I'd document a simple step-by-step method using Python as an alternative.


*NOTE: This guide assumes Python is not already installed and Windows is your operating system. (These steps can be easily adjusted/followed on Linux and MacOS.)


PREREQUISITES:


STEPS:

  1. Download the prerequisites
  2. Create a project folder to store your files; e.g., “C:\Users\Username\Desktop\TeslaTokens”
  3. Place: ChromeDriver, auth.tokens.py, and requirements.txt in “C:\Users\Username\Desktop\TeslaTokens”
  4. Install Python FOR ALL USERS and add to PATH (If you need help installing Python there are plenty of great videos out there explaining the process for each system)
  5. Launch a command window/terminal (e.g., PowerShell, Command Prompt, Terminal, etc.)
  6. Type:
    Code:
    CD C:\Users\Username\Desktop\TeslaTokens
  7. Press: ENTER
  8. Type:
    Code:
    pip install -r requirements.txt
  9. Press: ENTER
  10. At this point everything should be installed, configured and ready to go
  11. Then enter one of the below strings at the command prompt and hit ENTER:

If your Tesla account has MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password' -c 'passcode'

If your Tesla account does not have MFA enabled:
Code:
python3 ./auth.tokens.py -u 'email' -p 'password'

-u = Tesla account email
-p = Tesla account password
-c = Passcode generated by your authenticator app

MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword -c 123456

Non-MFA example:
Code:
python3 ./auth.tokens.py -u [email protected] -p someSuperSecurePassword

TIPS:

  • If python3 does not work try using just python
  • To check your Python install you can type:
    Code:
    python --version
♦♦♦ UPDATED Process & Code 04/27/2021: RealCarvedArt/tesla-oauth2 ♦♦♦

Thanks to @insaneoctane for discovering an issue (and the fix) with Tesla blocking "outdated browsers" ("It looks like you are using an outdated browser that will prevent you from accessing a variety of features across our site..."). The fix is to update the "USER_AGENT" line in the .py script to a current User Agent string in the following format:

Mozilla/5.0 (Linux; {Android Version}; {Build Tag etc.}) AppleWebKit/{WebKit Rev} (KHTML, like Gecko) Chrome/{Chrome Rev} Mobile Safari/{WebKit Rev}

• You can find valid User Agent strings here: https://developers.whatismybrowser.com/useragents/explore/operating_platform/pixel/
 
i can log on tesla account but when I try to get the token I have this error:
c:\..\TESLA Token\auth.tokens.py", line 116, in login
raise ValueError("Invalid credentials.")
ValueError: Invalid credentials.

C:\Users\Speedy\Desktop\TESLA Token>pyton3 ./auth.tokens.py -e '[email protected]' -p '123456789'
'pyton3' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Speedy\Desktop\TESLA Token>auth.tokens.py -e '[email protected]' -p '123456789'
Traceback (most recent call last):
File "C:\Users\Speedy\Desktop\TESLA Token\auth.tokens.py", line 268, in <module>
login(args)
File "C:\Users\Speedy\Desktop\TESLA Token\auth.tokens.py", line 116, in login
raise ValueError("Invalid credentials.")
ValueError: Invalid credentials.


i'm pretty sure the credentials are correct.
any help?
 
Hi, I am a Tesla owner in Europe with MFA enabled. I am trying to generate a token to use with Domoticz.
I get the following response from the python script:

DevTools listening on ws://127.0.0.1:57766/devtools/browser/6fb5314a-8381-47c1-922e-adf09e2c21a2
[0531/145010.407:INFO:CONSOLE(504)] "Refused to execute inline script because it violates the following Content Security Policy directive: "script-src www.recaptcha.net 'self' 'nonce-e9cbd375a92ebbce99b2'". Either the 'unsafe-inline' keyword, a hash ('sha256-+c4odmSNyaE9MUVh9F87zw9EUKahE+i/66Jp76JHZik='), or a nonce ('nonce-...') is required to enable inline execution.
", source: Tesla SSO - Sign In (504)
Traceback (most recent call last):
File "C:\temp\Domoticz@Pi\TeslaTokens\auth.tokens.py", line 266, in <module>
login(args)
File "C:\temp\Domoticz@Pi\TeslaTokens\auth.tokens.py", line 200, in login
code = parse_qs(resp.headers["location"])["Tesla SSO – Page Not Found"]
File "C:\Users\Frank\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'location'


Has there been a change on Tesla's side with a captcha or something?
Or can it be that the URL's the script is using are for North America only?
 
♦♦♦ UPDATED Process & Code 04/27/2021: RealCarvedArt/tesla-oauth2 ♦♦♦

Thanks to @insaneoctane for discovering an issue (and the fix) with Tesla blocking "outdated browsers" ("It looks like you are using an outdated browser that will prevent you from accessing a variety of features across our site..."). The fix is to update the "USER_AGENT" line in the .py script to a current User Agent string in the following format:

Mozilla/5.0 (Linux; {Android Version}; {Build Tag etc.}) AppleWebKit/{WebKit Rev} (KHTML, like Gecko) Chrome/{Chrome Rev} Mobile Safari/{WebKit Rev}

• You can find valid User Agent strings here: https://developers.whatismybrowser.com/useragents/explore/operating_platform/pixel/
Hi @CarvedArt ,
Thanks for the updated script.
However I get this error in line 18. Do you know the cause of this?
File "C:\Users\tom\Desktop\TeslaTokens\TeslaTokenV3.py", line 18, in <module>
import requests
ModuleNotFoundError: No module named 'requests'

Thanks in advance,
Tom
 
Hi @CarvedArt ,
Thanks for the updated script.
However I get this error in line 18. Do you know the cause of this?
File "C:\Users\tom\Desktop\TeslaTokens\TeslaTokenV3.py", line 18, in <module>
import requests
ModuleNotFoundError: No module named 'requests'

Thanks in advance,
Tom
Hi Tom,

Looks like you need to run the pip install -r requirements.txt command from the program directory. Steps 5 through 8 in the original post. Essentially, Python's telling you it requests isn't installed. You can install direct with pip install requests (at least on Linux that'd be the command; not sure about Windows offhand). But if you run that command direct, you'll likely be missing selenium (the other required module).
 
Hi Tom,

Looks like you need to run the pip install -r requirements.txt command from the program directory. Steps 5 through 8 in the original post. Essentially, Python's telling you it requests isn't installed. You can install direct with pip install requests (at least on Linux that'd be the command; not sure about Windows offhand). But if you run that command direct, you'll likely be missing selenium (the other required module).
Hi mankongde,

WHen I run the pip install -r requirements.txt I get this. To me it looks like every thing is OK?

C:\Users\tmidt\Desktop\TeslaTokens>pip install -r requirements.txt
Requirement already satisfied: requests==2.24.0 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from -r requirements.txt (line 1)) (2.24.0)
Requirement already satisfied: selenium==3.141.0 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from -r requirements.txt (line 2)) (3.141.0)
Requirement already satisfied: chardet<4,>=3.0.2 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from requests==2.24.0->-r requirements.txt (line 1)) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from requests==2.24.0->-r requirements.txt (line 1)) (2.10)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from requests==2.24.0->-r requirements.txt (line 1)) (1.25.11)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\tmidt\appdata\local\programs\python\python39\lib\site-packages (from requests==2.24.0->-r requirements.txt (line 1)) (2020.12.5)

Thnaks in advance,
Tom
 
♦♦♦ UPDATED Process & Code 06/11/2021: RealCarvedArt/tesla-oauth2 ♦♦♦
@CarvedArt , This has been the best step-by-step guide by far, thanks!

Unfortunately, using your latest TeslaTokenV3.py commit from June 11, 2021 with Python 3.9.6 Win64, I'm getting below error regardless of real or fake username/pw.

Post auth form success - 1 attempt(s). Traceback (most recent call last): File "E:\Downloads\Coding\Tesla Auth\TeslaTokens\TeslaTokenV3.py", line 276, in <module> login(args) File "E:\Downloads\Coding\Tesla Auth\TeslaTokens\TeslaTokenV3.py", line 233, in login code = parse_qs(resp.headers["location"])["https://auth.tesla.com/void/callback?code"] File "C:\Users\foo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__ return self._store[key.lower()][1] KeyError: 'location'
 
@CarvedArt , This has been the best step-by-step guide by far, thanks!

Unfortunately, using your latest TeslaTokenV3.py commit from June 11, 2021 with Python 3.9.6 Win64, I'm getting below error regardless of real or fake username/pw.

Post auth form success - 1 attempt(s). Traceback (most recent call last): File "E:\Downloads\Coding\Tesla Auth\TeslaTokens\TeslaTokenV3.py", line 276, in <module> login(args) File "E:\Downloads\Coding\Tesla Auth\TeslaTokens\TeslaTokenV3.py", line 233, in login code = parse_qs(resp.headers["location"])["https://auth.tesla.com/void/callback?code"] File "C:\Users\foo\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__ return self._store[key.lower()][1] KeyError: 'location'
Looks like it can no longer find the auth code in the location header. Unfortunately, I don't have time to troubleshoot atm, but as soon as I get a chance I'll look into it.
 
@CarvedArt , I know that you said you were busy, but I'm getting a similar, but different error that might be the same or different:

[0721/154148.223:INFO:CONSOLE(0)] "Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.", source: (0)
[0721/154148.963:INFO:CONSOLE(185)] "Locale changed: en-US", source: https://auth.tesla.com/static/js/tds4-i18n.js (185)
Traceback (most recent call last):
File "....py", line 274, in <module>
login(args)
File "....py", line 204, in login
code = parse_qs(resp.headers["location"])["Tesla SSO – Page Not Found"]
File "...\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'location'
 
@CarvedArt , I know that you said you were busy, but I'm getting a similar, but different error that might be the same or different:

[0721/154148.223:INFO:CONSOLE(0)] "Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.", source: (0)
[0721/154148.963:INFO:CONSOLE(185)] "Locale changed: en-US", source: https://auth.tesla.com/static/js/tds4-i18n.js (185)
Traceback (most recent call last):
File "....py", line 274, in <module>
login(args)
File "....py", line 204, in login
code = parse_qs(resp.headers["location"])["Tesla SSO – Page Not Found"]
File "...\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'location'
So I still don't have any free cycles, but I did look it over real quick and it appears that Tesla has added https://auth.tesla.com/captcha into the mix. See here for more: Tesla Added a Captcha Verification on the Login Page · Discussion #390 · timdorr/tesla-api