Step 3: Python code to generate a Keycloak token

In this section you will learn how to write code which automatically generates 6-digit TOTP code. Downloading an EODATA product will be covered in Step 4.

If you are using a virtual environment, enter it first.

Create file called genotp.py and paste into it the following code:

import pyotp  # to compute the TOTP code

secret = 'O5XU QRGL SFHU GS4R NZKU OUCG UURR QYSO'.replace(" ", "")
totp_secret = pyotp.TOTP(secret)
totp = totp_secret.now()
print(totp)

Variable secret will contain the value of 32-character code you got from Mobile Authenticator Setup screen, without the blanks. Then use secret in a call to the pyotp library to generate the TOTP, and print it on screen:

../_images/use_proper_code_to_print.png

Instead of the long string starting with O5XU, you will, of course, supply your own secret code you obtained from the browser form.

Run the program and get, say, the code of 169217; if you run it again, it will change to, say, 370764 and so on. You will, of course, get different six-digit codes but that is the whole point of this algorithm.

Note

The value generated may even be the same if you generate it more than once within the same 30-second interval.

Then go back to the browser where Mobile Authenticator Setup form is still present and enter one of these values into field One-time code. It has an asterisk and is thus a mandatory field to enter.

../_images/one_time_code.png

The other field, Device name, should contain text that, for you, uniquely identifies the device you are using to generate the codes.

You now have your own TOTP generator for the account, which frees you from mandatory presence of mobile devices or other software for OTP. Use the generator with one line of code:

python3 genotp.py

Start automating the process, by

  • creating a batch file to call the line above or

  • inserting that line into the already existing automation tools for your operating system or

  • using the code in genotp.py in a larger body of Python code that you may have available.

Note

You may use two Terminal windows at the same time, one to authenticate to the server and the other to generate the OTP. You still need to manually copy the generated TOTP from one window to another, but at least you do not depend on your mobile device to be around.