Reducing the manual effort when using OAuth 2.0 in Bruno
Although Bruno now 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.