Custom authentication

HMAC signatures, proprietary tokens and session-based flows - authentication schemes you implement yourself.

For authentication schemes not covered by built-in security types, you can implement your own validation logic in service code. Systems such as ServiceNow, SAP or Keysight Hawkeye use proprietary authentication mechanisms that work this way.

Validate incoming requests

Request headers are available through self.request.http.headers, with names lower-cased and dash-joined. For example, X-Hook-Signature becomes x-hook-signature.

HMAC signature verification

ServiceNow and similar systems sign webhook payloads with HMAC-SHA256. The service verifies the signature before it processes the request:

# -*- coding: utf-8 -*-

# stdlib
import hashlib
import hmac
from http import HTTPStatus

# Zato
from zato.server.service import Service

class HMACProtectedService(Service):
    """ Verifies an HMAC-SHA256 signature before processing a request.
    """
    name = 'demo.rest.hmac-protected'

    def handle(self) -> 'None':

        # A request with a signature header has it verified ..
        if signature := self.request.http.headers.get('x-signature'):
            is_valid = self.verify_signature(signature)

        # .. and a request without one is never valid ..
        else:
            is_valid = False

        # .. anything that is not valid is rejected before any processing ..
        if not is_valid:
            self.response.status_code = HTTPStatus.UNAUTHORIZED
            self.response.payload = {'error': 'Invalid or missing signature'}
            return

        # .. and only a request with a valid signature reaches this point.
        self.response.payload = {'status': 'ok'}

    def verify_signature(self, signature) -> 'bool':

        # The expected signature is computed over the raw request body
        secret = self.server.decrypt(self.config.api.hmac_secret)
        expected = hmac.new(
            secret.encode(),
            self.request.raw.encode(),
            hashlib.sha256
        ).hexdigest()

        return hmac.compare_digest(expected, signature)

To verify the flow, compute a signature over a test payload and send both:

# Generate a signature and call the endpoint
PAYLOAD='{"data":"test"}'
SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "your-secret" | cut -d' ' -f2)
curl -X POST http://localhost:11223/api/hmac/protected \
    -H "Content-Type: application/json" \
    -H "X-Signature: $SIGNATURE" \
    -d "$PAYLOAD"

Authenticate outgoing calls

Pass custom headers directly to the connection through the headers parameter.

Custom token header

For APIs using proprietary token-based authentication rather than standard OAuth 2.0, obtain and attach tokens yourself. Standard OAuth 2.0 client credentials are handled automatically by Bearer token security definitions.

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class CallWithCustomAuth(Service):
    """ Obtains a proprietary token and calls an API with it.
    """
    name = 'demo.rest.custom-auth'

    def handle(self) -> 'None':

        # Credentials from configuration ..
        client_id = self.config.api.client_id
        client_secret = self.server.decrypt(self.config.api.client_secret)

        # .. the auth provider exchanges them for a token ..
        auth_request = {
            'client_id': client_id,
            'client_secret': client_secret
        }
        conn = self.rest['Auth Service']
        auth_response = conn.post(auth_request)
        token = auth_response.data['access_token']

        # .. and the token authenticates the actual API call.
        headers = {'Authorization': f'Bearer {token}'}

        conn = self.rest['Target API']
        response = conn.get(headers=headers)

        self.response.payload = response.data

HMAC-signed requests

SAP and similar systems require HMAC signatures on outgoing requests:

# -*- coding: utf-8 -*-

# stdlib
import hashlib
import hmac
import json

# Zato
from zato.server.service import Service

class CallWithHMACAuth(Service):
    name = 'demo.rest.hmac-auth'

    def handle(self) -> 'None':

        payload = {'order_id': '12345', 'amount': 100}
        payload_json = json.dumps(payload)

        # The signature covers the exact bytes sent in the request body
        secret = self.server.decrypt(self.config.api.hmac_secret)
        signature = hmac.new(
            secret.encode(),
            payload_json.encode(),
            hashlib.sha256
        ).hexdigest()

        headers = {'X-Signature': signature}

        conn = self.rest['Signed API']
        response = conn.post(payload, headers=headers)

        self.response.payload = response.data

Session-based login and logout

APIs such as Keysight Hawkeye require an explicit login before API calls and a logout afterwards, with the session token from the login included in every request in between:

# -*- coding: utf-8 -*-

# stdlib
from traceback import format_exc

# Zato
from zato.server.service import Service

class SessionBasedAPICall(Service):
    name = 'demo.rest.session-based'

    def handle(self) -> 'None':

        # Credentials from configuration
        username = self.config.api.username
        password = self.config.api.password

        # Step 1: Log in to receive a session token
        login_conn = self.rest['API Login']
        login_response = login_conn.post({
            'username': username,
            'password': password
        })
        session_token = login_response.data['session_token']

        # Step 2: Call the API with the session token
        headers = {'X-Session-Token': session_token}

        try:
            api_conn = self.rest['API Endpoint']
            response = api_conn.get(headers=headers)
            self.response.payload = response.data

        except Exception:
            self.logger.warning('API call failed, e:`%s`', format_exc())
            raise

        finally:
            # Step 3: Log out to release the session
            logout_conn = self.rest['API Logout']
            logout_conn.post(headers=headers)

The finally block runs the logout even when the API call raises an error, so the session is always released.

GLPI sessions with the Connector SDK

GLPI is an open-source IT service management and asset management system, widely used in France, notably by public administrations, hospitals and universities.

The GLPI REST API keeps a session open across calls - each request includes an App-Token header, the initSession endpoint exchanges a user token for a Session-Token and the killSession endpoint closes the session. A connector built with the Connector SDK holds one such session for every service:

# -*- coding: utf-8 -*-

# stdlib
from http.client import UNAUTHORIZED

# requests
import requests

# Zato
from zato.common.sdk import Connector, CredentialsExpired, Field

if 0:
    from requests import Response
    from zato.common.typing_ import anydict, anydictnone, strstrdict

# The error code GLPI returns when a session expired or was closed
_session_token_invalid = 'ERROR_SESSION_TOKEN_INVALID'

class GLPIClient:
    """ A client for the GLPI REST API - it opens a session with the application token
    and the user token, and each request after that includes the session token.
    """
    def __init__(self, address:'str', app_token:'str', user_token:'str') -> 'None':
        self.api_url = f'{address}/apirest.php'
        self.user_token = user_token
        self.session_token = ''

        # Every request to GLPI includes the application token.
        self.http = requests.Session()
        self.http.headers['App-Token'] = app_token

    def _send(self, method:'str', path:'str', headers:'strstrdict', data:'anydictnone'=None) -> 'Response':

        # Send the request ..
        response = self.http.request(method, f'{self.api_url}/{path}', headers=headers, json=data)

        # .. GLPI describes an error as a list of its code and message ..
        if not response.ok:
            error_code, error_message = response.json()

            # .. an expired session is renewed by the platform, which then retries the call ..
            if response.status_code == UNAUTHORIZED and error_code == _session_token_invalid:
                raise CredentialsExpired(f'GLPI session expired at {self.api_url}')

            # .. and any other error goes to the caller.
            else:
                raise Exception(f'GLPI returned {response.status_code} {error_code} - {error_message}')

        return response

    def init_session(self) -> 'None':

        # Exchange the user token for a new session ..
        headers = {'Authorization': f'user_token {self.user_token}'}
        response = self._send('GET', 'initSession', headers)

        # .. and keep its token for the requests that follow.
        self.session_token = response.json()['session_token']

    def call(self, method:'str', path:'str', data:'anydictnone'=None) -> 'Response':
        headers = {'Session-Token': self.session_token}
        out = self._send(method, path, headers, data)
        return out

    def close_session(self) -> 'None':
        _ = self.call('GET', 'killSession')

    def get_item(self, item_type:'str', item_id:'int') -> 'anydict':
        response = self.call('GET', f'{item_type}/{item_id}')
        out = response.json()
        return out

    def create_item(self, item_type:'str', fields:'anydict') -> 'int':
        response = self.call('POST', item_type, {'input': fields})
        out = response.json()['id']
        return out

class GLPIConnector(Connector):
    """ Wraps the GLPI REST API as a connection type that services access through self.out.glpi.
    """
    type = 'glpi'

    # Configuration schema
    address = Field.Text()
    app_token = Field.Secret()
    user_token = Field.Secret()

    def create_client(self) -> 'GLPIClient':
        out = GLPIClient(self.config.address, self.config.app_token, self.config.user_token)
        out.init_session()
        return out

    def ping(self, client:'GLPIClient') -> 'None':
        _ = client.call('GET', 'getFullSession')

    def validate(self, client:'GLPIClient') -> 'None':
        """ Sends nothing before a call - an expired session is renewed when a call reports it.
        """

    def refresh_credentials(self) -> 'None':
        self.client.init_session()
        self.logger.info('GLPI session renewed for `%s`', self.name)

    def on_stop(self, client:'GLPIClient') -> 'None':
        client.close_session()

    def get_ticket(self, ticket_id:'int') -> 'anydict':
        out = self.client.get_item('Ticket', ticket_id)
        return out

    def create_ticket(self, name:'str', content:'str') -> 'int':
        out = self.client.create_item('Ticket', {'name': name, 'content': content})
        return out

A definition of the glpi type is created in an enmasse file under the custom_glpi key, and both tokens are stored encrypted:

custom_glpi:
  - name: My GLPI
    address: https://glpi.example.com
    app_token: my-app-token
    user_token: my-user-token

Services reach GLPI through self.out.glpi:

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Int, Service

class GetTicket(Service):
    """ Returns one ticket from GLPI.
    """
    name = 'demo.glpi.get-ticket'

    input = Int('ticket_id')

    def handle(self) -> 'None':
        conn = self.out.glpi['My GLPI']
        self.response.payload = conn.get_ticket(self.request.input.ticket_id)

class CreateTicket(Service):
    """ Creates a ticket in GLPI and returns its ID.
    """
    name = 'demo.glpi.create-ticket'

    input = 'name', 'content'

    def handle(self) -> 'None':
        conn = self.out.glpi['My GLPI']
        ticket_id = conn.create_ticket(self.request.input.name, self.request.input.content)
        self.response.payload = {'ticket_id': ticket_id}

When a session expires, GLPI answers with HTTP 401 and ERROR_SESSION_TOKEN_INVALID, the client raises CredentialsExpired, the platform runs refresh_credentials, which opens a new session, and the call is retried once, as described in the SDK reference.

See also

PageWhat it covers
AuthenticationThe built-in security types to check before implementing your own
WebhooksReceiving and verifying signed events from external systems
Calling REST APIsThe headers parameter and everything else a call accepts
Connector SDK referenceLifecycle methods, credential refresh and the behavior of every invocation

Learn more