Welcome to Part 2 of auth using Rails! Part 2 will cover what a hashing password is and authenticating users in our app.
What is a hashing password?
A hashing password is a one-way mathematical algorithm and turned into a chuck of data of a fixed size. If you noticed the hash password that was returned from my previous blog, using Postman, you’d notice the hash password doesn’t match the same as what was originally given. That’s because hash passwords can’t be reconstructed.
How is this used for authentication?
With the hash value in the database, each time the user signs in, the application can re-hash the given password and check it against the hash in the database. If the two match, the user is authenticated.
Now that we know what a hashing password is, lets start to authenticate our users in our app! I’ll provide a short and brief overview of how to do this. Continue reading for steps.
If you’ve been following along from Part 1, follow these next steps. First, you’ll want to install JWT (JSON Web Tokens). If you go to jwt.io, you’ll see what makes up a JWT. In short, JWT allows you to create three different sections: a headers, a payload, and a secret — each separated by a period. To install JWT on your backend, go to your Gemfile and add:
Next, to ensure JWT is installed, type the following in your command line:
Go to your routes.rb file and add the following code:
post “/login", to: “users#login”
Go to your users_controller.rb file and create your custom method for 'login’. For your login method, you’ll need to find the users username by params[:username]. Next, if the user and user password match, then it should render a JWT token. If either username or password don’t match, then it should return an unauthorized message. See my example below for further details:
Test this in Postman using the HTTP method POST and running localhost:3000/login. Remember to run your server (rails s).
Part 3 coming soon. Happy testing!