Python API

MFA

exception RPA.MFA.HOTPNotSetError

Bases: Exception

Raised when HOTP (HMAC One-Time Password) has not been set.

ERROR_MSG = 'HOTP (HMAC One-Time Password) can be set during the library initialization. With `Use MFA Secret From Vault` keyword or with `Set Counter Based OTP` keyword.'
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class RPA.MFA.MFA(vault_name: Optional[str] = None, vault_key: Optional[str] = None, mode: Optional[OTPMode] = OTPMode.TIME)

Bases: object

RPA.MFA is a library intended mainly for generating one-time passwords (OTP) and not only, as OAuth2 support was introduced lately.

Available with rpaframework version: 19.4.0

Based on the pyotp and requests_oauthlib packages. It provides support for both MFA with the * OTP related keywords and OAuth2 “Authorization Code Flow” with the * OAuth * related keywords.

In the below example the mfa secret we are reading from the Robocorp Vault is the passcode generated by the Authenticator service. The passcode value is stored into the Vault with key otpsecret.

Passcode is typically a long string (16-32 characters), which is provided in a form of QR image, but it can be obtained by requesting access to a string.

Note that same code can be used to add a mobile phone as a duplicate authentication device at the same time when the same code is added into the Vault.

Robot framework example usage:

*** Settings ***
Library     RPA.MFA
Library     RPA.Robocorp.Vault

*** Tasks ***
Generate time based code
    ${secrets}=    Get Secret   mfa
    ${code}=    Get Time Based OTP    ${secrets}[otpsecret]

Python example usage

from RPA.MFA import MFA
from RPA.Robocorp.Vault import Vault


def main():
    secrets = Vault().get_secret("mfa")
    code = MFA().get_time_based_otp(secrets["otpsecret"])
ROBOT_LIBRARY_DOC_FORMAT = 'REST'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
generate_oauth_url(auth_url: str, *, client_id: str, redirect_uri: str, scope: str, **kwargs) str

Generates an authorization URL which must be opened by the user to start the OAuth2 flow and obtain an authorization code as response.

The received response URL should be passed further with Get OAuth Token in order to complete the flow. Arbitrary keyword arguments can be passed to the keyword, which will be redirected to the wrapped oauthlib library method call.

Parameters
  • auth_url – Authorization endpoint to call the request on. (https URL usually ending with ‘/authorize’)

  • client_id – Client app ID. (generated by the provider)

  • redirect_uri – Redirect URL allowed by the Client app configuration. ( necessary for getting the code response)

  • scope – Space-separated string of permissions. (accepted during the consent screen)

Returns

Authorization URL string not containing any sensitive info in it. (call it with access_type=”offline” or set the right scope in the authorization URL for ensuring the existence of the refresh token)

Example: Robot Framework

*** Tasks ***
Start OAuth Flow
    ${auth_url} =    Generate OAuth URL
    ...     https://accounts.google.com/o/oauth2/auth
    ...     client_id=810482312368-19htmcgcj*******googleusercontent.com
    ...     redirect_uri=https://developers.google.com/oauthplayground
    ...     scope=https://mail.google.com
    ...     access_type=offline     prompt=consent  # explicit grant
    Log     Start OAuth2 flow: ${auth_url}

Example: Python

from RPA.MFA import MFA

lib_mfa = MFA()
auth_url = lib_mfa.generate_oauth_url(
    "https://accounts.google.com/o/oauth2/auth", ...
)
print(f"Start OAuth2 flow: {auth_url}")
get_counter_based_otp(counter: int, otp_passcode: Optional[str] = None)

Get counter based one time password using separately set passcode or by parameter otp_passcode. The counter index is given by the counter parameter.

Parameters
  • counter – the index of the counter

  • otp_passcode – the passcode provided by the Authenticator

get_oauth_token(token_url: str, *, client_secret: str, response_url: str, **kwargs) dict

Exchanges the code obtained previously with Generate OAuth URL for a token.

The refresh token from the returned dictionary can be used further with the Refresh OAuth Token keyword in order to obtain a new access token when the previous one expires. (usually after one hour) Arbitrary keyword arguments can be passed to the keyword, which will be redirected to the wrapped oauthlib library method call.

Parameters
  • token_url – Token endpoint used with a POST request in order to retrieve the token data. (https URL usually ending with ‘/token’)

  • client_secret – Client app secret. (generated by the provider)

  • response_url – The final URL containing the authorization code found in the address bar after authenticating and authorizing the Client app through the authorization URL.

Returns

A dictionary containing the access token, metadata and optionally the refresh token.

Example: Robot Framework

*** Tasks ***
Finish OAuth Flow
    ${token} =      Get OAuth Token
    ...     https://accounts.google.com/o/oauth2/token
    ...     client_secret=GOCSPX-******mqZAW89
    ...     response_url=${resp_url}  # redirect of `Generate OAuth URL`

Example: Python

from RPA.MFA import MFA

lib_mfa = MFA()
lib_mfa.get_oauth_token("https://accounts.google.com/o/oauth2/token", ...)
get_time_based_otp(otp_passcode: Optional[str] = None)

Get time based one time password using separately set passcode or by parameter otp_passcode.

Parameters

otp_passcode – the passcode provided by the Authenticator

property oauth: OAuth2Session

Raises if there’s no OAuth2 session already created.

refresh_oauth_token(token_url: str, *, client_id: Optional[str] = None, client_secret: str, refresh_token: Optional[str] = None, **kwargs) dict

Refreshes the token as the access one usually expires after 1h and the refresh one never expires. (as long as it doesn’t get revoked)

The effect of this keyword is similar to Get OAuth Token, but this time you refresh unattended an already existing token by receiving a new one instead. Arbitrary keyword arguments can be passed to the keyword, which will be redirected to the wrapped oauthlib library method call.

Parameters
  • token_url – Token endpoint used with a POST request in order to refresh the token data. (https URL usually ending with ‘/token’)

  • client_id – Client app ID. (generated by the provider)

  • client_secret – Client app secret. (generated by the provider)

  • refresh_token – Refresh token string found in the dictionary obtained with Get OAuth Token or Refresh OAuth Token.

Returns

A token dictionary containing a new access token and updated metadata. (the refresh token inside isn’t guaranteed to remain constant)

Example: Robot Framework

*** Tasks ***
Refresh OAuth Flow
    ${token} =      Refresh OAuth Token
    ...     https://accounts.google.com/o/oauth2/token
    ...     client_id=810482312368-19htmcgcj*******googleusercontent.com
    ...     client_secret=GOCSPX-******mqZAW89
    ...     refresh_token=${token}[refresh_token]  # from `Get OAuth Token`

Example: Python

from RPA.MFA import MFA

lib_mfa = MFA()
lib_mfa.refresh_oauth_token(
    "https://accounts.google.com/o/oauth2/token", ...
)
set_counter_based_otp(otp_passcode: str)

Set counter based OTP with passcode.

Parameters

otp_passcode – the passcode provided by the Authenticator

set_time_based_otp(otp_passcode: str)

Set time based OTP with passcode.

Parameters

otp_passcode – the passcode provided by the Authenticator

use_mfa_secret_from_vault(vault_name: str, vault_key: str, mode: OTPMode = OTPMode.TIME)

Set time or counter based OTP with passcode stored in the Robocorp Vault named with vault_name under key of vault_key.

Parameters
  • vault_name – name of the vault storing the passcode

  • vault_key – name of the vault key storing the passcode value

exception RPA.MFA.OAuth2NotSetError

Bases: Exception

Raised when OAuth2 session object isn’t initialized but used.

ERROR_MSG = 'OAuth2 session required but not initialized, please call the `Generate OAuth URL` keyword first.'
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class RPA.MFA.OTPMode(value)

Bases: Enum

Enumeration for type of OTP to use.

COUNTER = 'COUNTER'
TIME = 'TIME'
exception RPA.MFA.TOTPNotSetError

Bases: Exception

Raised when TOTP (Time-based One-Time Password) has not been set.

ERROR_MSG = 'TOTP (Time-based One-Time Password) can be set during the library initialization. With `Use MFA Secret From Vault` keyword or with `Set Time Based OTP` keyword.'
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.