From e4a1e6a472a00db5dd14552bfcbcd3c5831f58f5 Mon Sep 17 00:00:00 2001 From: Bryan Joshua Pedini Date: Tue, 25 Aug 2026 13:47:18 +0200 Subject: [PATCH] feat: bearer auth for netbox 4.5 v2 api tokens v2 tokens (nbt_.) are sent as Authorization: Bearer, legacy tokens keep the Token scheme; NetBox drops legacy token support in 4.7. --- netbox_inventory.py | 14 +++++++++++++- tests/test_inventory.py | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/netbox_inventory.py b/netbox_inventory.py index 0bea7b5..bcf8da5 100755 --- a/netbox_inventory.py +++ b/netbox_inventory.py @@ -66,6 +66,18 @@ def _extract_error_message(response: requests.Response) -> str: return f"NetBox API error: HTTP {response.status_code}" +def auth_header(token: str) -> str: + """ + Build the Authorization header value for a NetBox API token. + + Version 2 tokens (NetBox 4.5+, "nbt_.") use the Bearer + scheme, legacy tokens the Token scheme. + """ + if token.startswith("nbt_"): + return f"Bearer {token}" + return f"Token {token}" + + class NetBoxClient: """Thin wrapper around the NetBox REST API.""" @@ -76,7 +88,7 @@ class NetBoxClient: self._session.verify = verify_ssl self._session.headers.update( { - "Authorization": f"Token {token}", + "Authorization": auth_header(token), "Accept": "application/json", } ) diff --git a/tests/test_inventory.py b/tests/test_inventory.py index e28cbd8..f3a9837 100644 --- a/tests/test_inventory.py +++ b/tests/test_inventory.py @@ -16,6 +16,14 @@ def make_client() -> inv.NetBoxClient: return inv.NetBoxClient(NETBOX_URL, "token", verify_ssl=True, timeout=5) +class TestAuthHeader: + def test_legacy_token_uses_token_scheme(self): + assert inv.auth_header("0123456789abcdef") == "Token 0123456789abcdef" + + def test_v2_token_uses_bearer_scheme(self): + assert inv.auth_header("nbt_abc.def") == "Bearer nbt_abc.def" + + class TestStripPrefix: def test_strips_prefix_length(self): assert inv.strip_prefix("192.0.2.10/24") == "192.0.2.10"