API Authorization

To connect to BidSwitch using one of its APIs, use the following steps.

  • Create an API user in your myBidSwitch UI account.

  • Using this user’s credentials, get your API token by making a POST request to the BidSwitch authorization endpoint.

  • Pass this token in your request header Authorization:Bearer ${TOKEN}

Creating an API User

To create a user profile that can receive API Tokens, use the following steps. Once created you can get get a permanent token or request short lived temporary tokens:

  1. From the BidSwitch UI, select Users ‣ Add User.

  2. From the User Role dropdown menu, select API Account.

Temporary and Refresh Tokens

To get a temporary auth token for your integration, use the following steps.

  • Make a HTTP POST request to the auth endpoint.

  • The response will contain your access token, its expiration time, and refresh token. You can use the access token to perform API requests until the token expires.

  • Refresh tokens should be used in long-running applications. To extend your session once your access token expires, get a new access token and a new refresh token using the prior refresh token (possibly multiple times).

Auth Token POST Details

Endpoint Info

Description

endpoint

https://iam.bidswitch.com/auth/realms/bidswitch/protocol/openid-connect/token

Method

POST

headers

Content-Type and Accept {'Content-Type': 'application/x-www-form-urlencoded', 'accept': 'application/json'}

username

(Required) Your UI username

password

(Required) Your UI password

scope

The service to which your user token should grant you access, e.g. scope=openid email profile

Example Using Curl
curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' -H 'accept: application/json' -d 'client_id=public-client&grant_type=password&username={username}&password={password}&scope=openid email profile' 'https://iam.bidswitch.com/auth/realms/bidswitch/protocol/openid-connect/token'
Sample AUTH Response
{
  "access_token":"token",
  "expires_in":300,
  "refresh_expires_in":28800,
  "refresh_token":"refresh_token",
  "token_type":"Bearer",
  "not-before-policy":0,
  "session_state":"e51f1ad5-e7f0-444c-bcc0-1f6b392a8de1",
  "scope":"profile roles email"
}

Complete Example

#!/usr/bin/python3
import logging
import os
from typing import Tuple

from requests import post
from requests import request

IAM_URL = 'https://iam.bidswitch.net'
IAM_REALM = 'bidswitch'
PUBLIC_CLIENT_ID = 'public-client'
RESOURCE_METHOD = 'GET'
RESOURCE_URL = 'https://oauth2-proxy-demo.test.it.bidswitch.net'
TEST_USERNAME = os.environ['TEST_USERNAME']
TEST_PASSWORD = os.environ['TEST_PASSWORD']  # Please keep password secret!

LOGGER = logging.getLogger(__name__)
logging.basicConfig(format='[%(asctime)s %(levelname)s] [%(name)s] %(message)s', level=logging.DEBUG)


def public_login(
        username: str, password: str, offline_access: bool,
        iam_url: str, iam_realm: str, client_id: str) -> Tuple[str, str]:
    """
    Log in to BidSwitch IAM: get OAuth2 Access and Refresh Tokens
    :param username: Username
    :param password: Password
    :param offline_access: Is offline access required
    :param iam_url: Base URL of IAM server
    :param iam_realm: IAM realm
    :param client_id: Public client ID
    :return: Tuple: OAuth2 Access Token and OAuth2 Refresh Token
    """
    scope = ['openid', 'email', 'profile']
    if offline_access:
        scope.append('offline_access')

    response = post(
        url=f'{iam_url}/auth/realms/{iam_realm}/protocol/openid-connect/token',
        data={
            'client_id': client_id,
            'grant_type': 'password',
            'username': username,
            'password': password,
            'scope': ' '.join(scope)
        }
    )
    assert response.status_code == 200, f'{response.status_code}: {response.text}'

    return response.json()['access_token'], response.json()['refresh_token']


def refresh_session(
        refresh_token: str,
        iam_url: str = IAM_URL, iam_realm: str = IAM_REALM) -> Tuple[str, str]:
    """
    Refresh user session, i.e. get new OAuth2 Access Token
    :param refresh_token: OAuth2 Refresh Token
    :param iam_url: Base URL of IAM server
    :param iam_realm: IAM realm
    :return: Tuple: OAuth2 Access Token and OAuth2 Refresh Token
    """
    response = post(
        url=f'{iam_url}/auth/realms/{iam_realm}/protocol/openid-connect/token',
        data={
            'client_id': PUBLIC_CLIENT_ID,
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token
        }
    )
    assert response.status_code == 200, f'{response.status_code}: {response.text}'

    return response.json()['access_token'], response.json()['refresh_token']


def is_access_authorized(access_token: str, resource_method: str, resource_url: str) -> bool:
    """
    Access web resource protected with BidSwitch IAM
    :param access_token: OAuth2 Access Token
    :param resource_method: HTTP method to access protected resource
    :param resource_url: URL of protected resource
    :return: If resource access is authorized
    """
    response = request(
        method=resource_method,
        url=resource_url,
        headers={
            'Authorization': f'Bearer {access_token}'
        },
        allow_redirects=False
    )

    if response.status_code == 200 and 'Demo web application' in response.text:
        LOGGER.info('Resource access authorized')
        return True

    return False


def demo_offline_access():
    # Get offline refresh token and store it
    __, refresh_token = public_login(
        TEST_USERNAME, TEST_PASSWORD, True, IAM_URL, IAM_REALM, PUBLIC_CLIENT_ID)

    for _ in range(3):
        # Reuse offline refresh token to get new access token
        access_token, __ = refresh_session(refresh_token)
        assert is_access_authorized(access_token, RESOURCE_METHOD, RESOURCE_URL)


def demo_online_access():
    # Get temporary refresh token
    __, refresh_token = public_login(
        TEST_USERNAME, TEST_PASSWORD, False, IAM_URL, IAM_REALM, PUBLIC_CLIENT_ID)

    for _ in range(3):
        # Get new access token and temporary refresh token using temporary refresh token
        access_token, refresh_token = refresh_session(refresh_token)
        assert is_access_authorized(access_token, RESOURCE_METHOD, RESOURCE_URL)


if __name__ == '__main__':
    demo_offline_access()
    demo_online_access()