Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.apinizer.com/llms.txt

Use this file to discover all available pages before exploring further.

This script parses the incoming request’s Authorization header and extracts the user identity. It supports both Basic Auth and JWT (Bearer) formats.
Field selection: By default, the script looks at the iss (issuer) claim inside the JWT. If your username is in sub or preferred_username, update the parsed?.iss part in the code to the appropriate field.

Usage and customization

  • JWT usage: If the username is not in the iss claim, change the corresponding field (e.g. parsed?.sub) in the script after adding it.
  • Custom formats: If the header is sent without the “Basic” or “Bearer” prefix, you may need to adapt the script for that case.
  • Fallback: If the header does not match the standard formats, the first 6 characters of the current string are used as a safe fallback.

Groovy script

import java.util.Base64
import groovy.json.JsonSlurper

def auth = requestHeaderMapFromClient.get("Authorization")
def result = "unknown"

if (auth && !auth.trim().isEmpty()) {

    if (auth.startsWith("Basic ")) {
        try {
            def base64Part = auth.length() > 6 ? auth.substring(6) : ""
            def decoded = new String(Base64.decoder.decode(base64Part), "UTF-8")
            result = decoded.contains(":") ? decoded.split(":")[0] : decoded
        } catch (Exception e) {
            result = null
        }
    }

    else if (auth.startsWith("Bearer ")) {
        def token = auth.length() > 7 ? auth.substring(7) : ""

        if (token.count(".") == 2) {
            try {
                def payload = token.split("\\.")[1]
                def json = new String(Base64.urlDecoder.decode(payload), "UTF-8")
                def parsed = new JsonSlurper().parseText(json)
                result = parsed?.iss
            } catch (Exception e) {
                result = null
            }
        } else {
            result = token.substring(0, Math.min(6, token.length()))
        }
    }

    else {
        result = auth.substring(0, Math.min(6, auth.length()))
    }
}

request_usernameOrKey = result
After adding the script, check which claim (e.g. sub, preferred_username) your Identity Provider (Keycloak, Auth0, etc.) uses in the JWT for the username.

Error cases

  • Unknown result: If the result is unknown, the script is not running, the header is empty, or the user info could not be read from the expected field.
  • Decode errors: If Base64 decoding fails, the result is null.