I need to document a RubyOnRails API with Postman but I don’t know how to set up the authorization for the requests that need token. I’m using devise_token_auth gem
When you use devise_token_auth the format of the cURL is the following:
curl -XGET -v -H 'Content-Type: application/json' -H 'access-token: lW1c60hYkRwAinzUqgLfsQ' -H 'client: W_xCQuggzNOVeCnNZbjKFw' -H "uid: [email protected]" http://domain/api/v1/auth/validate_token
So you need the next parameters to access: access-token, client, uid, url
To get them you need to follow these instructions:
You could set the values as local variables in an environment to call them in every request instead of pasting them in each header.
In case you got an Authorization error after complete this guide
{
"errors": [
"Authorized users only."
]
}
This is because sometimes the access-token is configured to change each time the client queries the API, to change this configuration only add the following line to config/initializers/devise_token_auth.rb
config.change_headers_on_each_request = false
REST API Testing - Postman behaving as different client after each request
Having to set config.change_headers_on_each_request = false
may not be ideal for everyone.
I was able to have Postman automatically save access-token, client, and uid to environment variables (in my case I used ACCESS_TOKEN, ACCESS_CLIENT, and ACCESS_UID) with a Postman test script:
responseHeaders['access-token'] && pm.environment.set("ACCESS_TOKEN", responseHeaders['access-token']);
responseHeaders['client'] && pm.environment.set("ACCESS_CLIENT", responseHeaders['client']);
responseHeaders['uid'] && pm.environment.set("ACCESS_UID", responseHeaders['uid']);
This script first tests to make sure the token was returned (in a failed request a new token is not returned), then saves them to your environment variables.
Then using a Pre Request script I have those variables added to the header automatically.
pm.request.headers.upsert({key: 'access-token', value: pm.variables.get("ACCESS_TOKEN") });
pm.request.headers.upsert({key: 'client', value: pm.variables.get("ACCESS_CLIENT") });
pm.request.headers.upsert({key: 'uid', value: pm.variables.get("ACCESS_UID") });
I add these at the Collection instead of each specific request in Postman:
Collection Edit screen, Pre-request Scripts tab
Collection Edit screen, Tests tab
Then all I need to do before I start making requests, is to make a Login request to get the initial token (which will get saved thanks to our Test script). Each successful request after that will automatically save and use the newest token, allowing you to test your API without having to modify the config settings inside your Rails app.
Hope this can help anyone who finds this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With