A bearer is a type of authentication token that a user or system presents to verify its identity. Bearer tokens are commonly used in web applications, APIs, and network protocols. The term bearer means that anyone who possesses the token is considered authenticated, without requiring additional verification. Bearer tokens are simple to implement but require strong protection. Since possession of the token alone grants access, unauthorized individuals who get the token can use it as if they were the legitimate user.
Configurations
The bearer mechanism has the following configurations:
Configuration | Description |
|---|---|
Bearer Token | The token string represents the user's authentication and authorization claims. |
Add the token as part of the Query parameter | You can include a bearer token as a query parameter in an HTTP request. This approach is generally discouraged because passing tokens in the URL exposes them in browser history, logs, caches, and monitoring systems, increasing the risk of unauthorized access. Using the If you still need to pass the token as a query parameter, you can append it to the URL as shown below:
|
Add the token as part of the Header (Recommended) | Adding a bearer token in the request header is the recommended and standard practice for bearer token authentication in HTTP requests. You can include the token in the
|
Add the token as part of the Cookie | Bearer tokens are usually not stored in cookies because doing so introduces security risks. Storing authentication tokens in cookies can make them vulnerable to attacks, such as cross-site scripting (XSS) and cross-site request forgery (CSRF). The recommended and more secure approach is to send bearer tokens in the If you still wish to store a bearer token in a cookie, you can set the cookie using server-side code. |
Example
The following are some samples that you can use to configure the Bearer mechanism in the Advanced mode:
Sample 1
def bearer_token_hook(scanctx: ScanContext, pluginctx: PluginContext, testcase: TestCase, **kwargs) -> list[Assertion]:
attributes = testcase.get_attributes()
bearer_token = "bearer_token"
set_key = "token_identifier_key"
bearer_format = "bearer_format_template"
bearer_value = bearer_format.replace("{{value}}", str(bearer_token))
auth_attr = ""
# set user
normal_user = True
bola_user = False
set_header = True
set_cookie = False
set_query = False
# set api key in header
if set_header:
attributes.set("mutated.auth.attribute", "mutated.http.request.header.%s" % set_key)
auth_attr = "mutated.http.request.header.%s" % set_key
# set api key in query
if set_query:
attributes.set("mutated.auth.attribute", "mutated.http.request.query.param.%s" % set_key)
auth_attr = "mutated.http.request.query.param.%s" % set_key
# set api key in cookie
if set_cookie:
attributes.set("mutated.auth.attribute", "mutated.http.request.cookie.%s" % set_key)
auth_attr = "mutated.http.request.cookie.%s" % set_key
if normal_user:
attributes.set("mutated.role.user", bearer_value)
attributes.set(auth_attr, bearer_value)
if bola_user:
attributes.set("mutated.role.bolauser", bearer_value)
return []Sample 2
import requests
import time
import uuid
from traceable.ast.testsuite.assertion import Assertion
from traceable.ast.context import ScanContext, PluginContext
from traceable.ast.testsuite.plugin import TestCase
from traceable.config import logger
AUTH_URL = "TOKEN_VALUE"
USERNAME = "TOKEN_VALUE"
PASSWORD = "TOKEN_VALUE"
def perform_auth():
payload = {
"username": USERNAME,
"password": PASSWORD
}
headers = {
"Content-Type": "application/json",
"Cookie": f"XSRF-TOKEN={uuid.uuid4()}"
}
response = requests.post(AUTH_URL, json=payload, headers=headers)
response.raise_for_status()
try:
response_json = response.json()
if isinstance(response_json, str) and response_json.count('.') in [2, 4]:
logger.info("Received token from auth service")
return {
"access_token": response_json.strip(),
"expires_in": 3600,
"token_type": "Bearer",
"scope": "",
}
elif isinstance(response_json, dict) and "access_token" in response_json:
return {
"access_token": response_json["access_token"],
"expires_in": response_json.get("expires_in", 3600),
"token_type": response_json.get("token_type", "Bearer"),
"scope": response_json.get("scope", ""),
}
else:
raise Exception(f"Unexpected response: {type(response_json)}")
except requests.exceptions.JSONDecodeError:
response_text = response.text.strip()
if response_text.count('.') in [2, 4]:
logger.info("Received token as plain text")
return {
"access_token": response_text,
"expires_in": 3600,
"token_type": "Bearer",
"scope": "",
}
else:
raise Exception(f"Invalid token format: {response_text[:50]}...")
def expired(seconds, timestamp):
return time.time() - timestamp > seconds
def test_hook_script(
scanctx: ScanContext, pluginctx: PluginContext, testcase: TestCase, **kwargs
) -> list[Assertion]:
return bearer_token_hook(scanctx, pluginctx, testcase, **kwargs)
def bearer_token_hook(
scanctx: ScanContext, pluginctx: PluginContext, testcase: TestCase, **kwargs
) -> list[Assertion]:
attributes = testcase.get_attributes()
auth_attr = "mutated.http.request.header.authorization"
attributes.set("mutated.auth.attribute", auth_attr)
auth_response = scanctx.get("auth_response", {})
if ("access_token" not in auth_response or
("expires_in" in auth_response and "timestamp" in auth_response and
expired(auth_response["expires_in"], auth_response["timestamp"]))):
logger.info("Getting new token")
auth_response = perform_auth()
auth_response["timestamp"] = time.time()
scanctx.set("auth_response", auth_response)
else:
logger.info("Using cached token")
# Set authorization header
token_type = auth_response.get("token_type", "Bearer")
attributes.set(auth_attr, f"{token_type} {auth_response['access_token']}")
return []
if __name__ == "__main__":
logger.info("Testing stablecoin authentication")
try:
auth_response = perform_auth()
logger.info("Authentication successful!")
logger.info(f"Token type: {auth_response.get('token_type')}")
logger.info(f"Expires in: {auth_response.get('expires_in')} seconds")
logger.info(f"Token preview: {auth_response['access_token'][:50]}...")
except Exception as e:
logger.exception(f"Authentication failed: {e}")
raiseSample 3
def bearer_token_hook(scanctx: ScanContext, pluginctx: PluginContext, testcase: TestCase, **kwargs) -> list[Assertion]:
attributes = testcase.get_attributes()
bearer_token = "TOKEN_VALUE"
set_key = "Auth-Graviteeio-APIM"
bearer_format = "bearer_format_template"
bearer_value = bearer_format.replace("{{value}}", str(bearer_token))
auth_attr = ""
# set user
normal_user = True
bola_user = False
set_header = False
set_cookie = True
set_query = False
# set api key in header
if set_header:
attributes.set("mutated.auth.attribute", "mutated.http.request.header.%s" % set_key)
auth_attr = "mutated.http.request.header.%s" % set_key
# set api key in query
if set_query:
attributes.set("mutated.auth.attribute", "mutated.http.request.query.param.%s" % set_key)
auth_attr = "mutated.http.request.query.param.%s" % set_key
# set api key in cookie
if set_cookie:
attributes.set("mutated.auth.attribute", "mutated.http.request.cookie.%s" % set_key)
auth_attr = "mutated.http.request.cookie.%s" % set_key
if normal_user:
attributes.set("mutated.role.user", bearer_value)
attributes.set(auth_attr, bearer_value)
if bola_user:
attributes.set("mutated.role.bolauser", bearer_value)
return []