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

CarvedArt

Member
Aug 12, 2020
16
9
Mars
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
 

insaneoctane

Active Member
Apr 6, 2016
3,521
6,625
Southern California
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?
 

CarvedArt

Member
Aug 12, 2020
16
9
Mars
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?
 

insaneoctane

Active Member
Apr 6, 2016
3,521
6,625
Southern California
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:

insaneoctane

Active Member
Apr 6, 2016
3,521
6,625
Southern California
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

CarvedArt

Member
Aug 12, 2020
16
9
Mars
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!
 

CarvedArt

Member
Aug 12, 2020
16
9
Mars
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/
 

Spectra207

Member
Apr 7, 2021
16
17
Ottawa, Canada
I use Firefox as my browser (don't have Chrome installed). Is the Chrome browser a prerequisite for this script? If so, why is that since as far as I can tell this doesn't involve the browser? Sorry for the noob question.
 
Jan 20, 2020
203
95
Crawley
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?
 

FrugalFrank

Member
Feb 25, 2019
115
130
Zaanstad, Netherlands
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\[email protected]\TeslaTokens\auth.tokens.py", line 266, in <module>
login(args)
File "C:\temp\[email protected]\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?
 

midtboell

New Member
Feb 2, 2021
3
0
Europe
♦♦♦ 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
 

mankongde

New Member
Jun 1, 2021
1
0
SF Bay Area, USA
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).
 

midtboell

New Member
Feb 2, 2021
3
0
Europe
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
 

About Us

Formed in 2006, Tesla Motors Club (TMC) was the first independent online Tesla community. Today it remains the largest and most dynamic community of Tesla enthusiasts. Learn more.

Do you value your experience at TMC? Consider becoming a Supporting Member of Tesla Motors Club. As a thank you for your contribution, you'll get nearly no ads in the Community and Groups sections. Additional perks are available depending on the level of contribution. Please visit the Account Upgrades page for more details.


SUPPORT TMC
Top