Reducing the manual effort when using OAuth 2.0 in Bruno
Obsolete article: Bruno 2.0 comes with automatic token injection, auto-fetch and refresh. Scripting, as described in this article, is no longer necessary. However, at least the end of this article can still be helpful in case of connection problems.
Although Bruno comes with built-in support to fetch access tokens via OAuth 2.0, we still need to add the access token to each request manually. We can significantly reduce the manual workload with little additional effort.
As we usually have multiple requests in a collection that require authentication, we configure the authentication on collection level. In the Auth
tab, we choose OAuth 2.0
and configure everything as needed. On the bottom, we press the Get Access Token
button to verify that the authentication works.
Next, we set a variable named oauth_access_token
every time an authentication request was made. In the Script
tab, we put the following code under Post Response
.
if (res.body.access_token) {
bru.setVar("oauth_access_token", res.body.access_token)
}
The if-clause is important here, because without it, every normal request will overwrite the variable with undefined
.
Now, we can use the variable with our access token in the header of our requests. In the Headers
tab, we add a header Authorization
with value Bearer {{oauth_access_token}}
. Whenever the variable is highlighted red, or we receive an unauthorized error message, we must go to the Auth
tab and press the Get Access Token
button again. Depending on our needs, we can configure the header on the collection level or per request.
And that's it already. We can run authorized requests now without any further configuration until our access token expires.
Special Cases
While the procedure is always the same, it sometimes needs some additional configuration to work.
Microsoft Entra ID requires the Origin
header to be set when we use the callback URL of a single-page application. Otherwise, we just get the response invalid_request
from Bruno. After some debugging, it turns out that the actual error states "AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin request". In the Headers tab of our collection, we just need to add the Origin
header with value http://localhost
.
Alternatively, choose any callback URL that is configured in the "Mobile and desktop applications" section of your App Registration in the Azure Portal. This also works for Bruno 2.0.
- Update 2025–02–07: Describe extra configuration for Microsoft Entra ID.
- Update 2025-04-04: Mark article as obsolete and update extra configuration for Microsoft Entra ID.