Hooray we've made it to part 3 in a 3 part series on basic authentication in Ruby on Rails! Checkout Part 1 and Part 2 if you haven't already. For part 3 the goal will be to verify and protect resources with tokens.
In the previous posts we've created a Ruby on Rails API for a clothing store that has users
. Now we're going to make it so only logged in users
can create items
. Let's generate this new resource item
.
In your terminal:
rails g controller items
rails g model item
Now we setup the route and the migration, items
will have a name and a price.
Now we'll setup a basic ItemsController
where anyone can create an item
and index all of the items
.
In your terminal run rails db:migrate
and start your server rails s
so we can test this in Postman. A get
request to localhost:3000/items
should show an empty list of items
. So let's make sure we can create an item
with a post
request.
Now let's make it so only a logged in user
with a valid token can create an item
. Let's update the create
method in the ItemsController
. When making HTTP requests the token is stored in the Authorization
header so we will want access to that. If the authorization header is absent from the request we can end the conversation right there and present an error. Else, we'll want to split the token from the authorization header at " " since the header includes "Bearer " prior to the token itself. Now we want to DECODE the token (that we encoded in the AuthorizationController
) so we can use it.
Let's try to add a shirt with no token present
Now let's try it with my token, the token can be obtained by making a post
request to the login
route with a valid username and password. Enter your token under the "Authorization" header and make sure to select "Bearer Token"
And lastly let's tamper with this token and make sure it only works with a valid token. I've added some "xxxxx" to the end of my token and will try to add a sweater to our items list.
Alright fam we've made it! The item
resource has been successfully protected! Thanks again for reading and as always please let me know if you have any questions, comments, suggestions, etc. because as a developer I'm always learning so there's always more to know!
Top comments (0)