Javascript Web Tokens

Lawson Hung
2 min readMay 22, 2020

Authentication is something that I am still struggling with. So I’m going to talk about how to log a user in, in an attempt to better understand what’s happening under the hood.

Postman is used for testing the backend to make sure you’re getting the right response, without the need for a front end framework. http://localhost:3000/login redirects to this method in Ruby:

def login# find a useruser = User.find_by(username: params[:username])# if user exists, see if they really are the user via a passwordis_authenticated = user.authenticate(params[:password])# if all is well, send back the userif is_authenticated# Moving to ApplicationController for refactoring# payload = { user_id: user.id }# # JWT.encode(payload, secret, hash algorithm)# token = JWT.encode(payload, 'mysecretsecretSHHHH', 'HS256')render json: {token: create_token(user.id)} # I want a token insteadelserender json: {errors: ['Wrong username or password, Youre not real... sorry']},status: 422endend

We first have to find the user. params[:username] refers to the params passed into the body of Postman. So we’re trying to find the User object with User.find_by(username: params[:username]) . And assign that to a variable, user.

We then authenticate the user with user.authenticate(params[:password]) . This is basically like entering your password on a website. If this returns true and the user is_authenticated, we can then create a Javascript Web Token. First, we must define the payload. This is simply the ID of the user, payload = { user_id: user.id } .

The syntax for JWTs is as follows: JWT.encode(payload, secret, hash algorithm) . We have define the payload. The secret is a string that is stored as an environmental variable on your computer. You use this to sign the token, sort of like a password for the server/backend. The secret secret I use here is mysecretsecretSHHHH. The hash algorithm is what you want to use to encode the token. In our case, the hash algorithm is HS256.

Lastly, we want to render the token as json, so render json: {token: create_token(user.id)} .

Otherwise, we return an error: render json: {errors: [‘Wrong username or password, Youre not real… sorry’]},status: 422 .

That’s all for now, and enjoy your quarantine!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Lawson Hung
Lawson Hung

No responses yet

Write a response