Today we’ll be continuing by learning how to handle use-cases where our user’s authentication token is either invalid or missing.
Handling an Invalid token against an API
When a user makes a request with an invalid token we need to make sure we’re alerting them of this error.
We can do this by returning a JSON error like so:
In order to be able to test this, we can make an API request without an authentication token and then make our spec pass in this token instead. Lets add a new test file covering our user’s authentication behavior. Inside of
spec/apis/v1/authentication_spec.rb we can add:
Now that we have defined the user token as an empty string, GET will pass it in as the token for our spec. Running
rspec spec/apis/v1/authentication_spec.rb shows that our test fails. This is because when we attempt to make a request without a valid token, the call to
User.find_by_authentication_token in our
base_cotroller will return
We can add a condition where if the user has not been found an error will be triggered. Lets add the following code to our
authenticate_user method in
nil we have now built in a JSON error response that will be triggered, and running
rspec spec/apis/v1/project_spec.rb should show the spec passing.
We now have the
apis/v1/projects URL returning a list of only the projects that a user is authorized to read, and we have used Devise’s token authentication functionality to verify which user this is.
Categories: Ruby on rails