DEV Community

Matt Gahrns
Matt Gahrns

Posted on

What is a JWT?

The JSON Web Token

JWT stands for JSON Web Token. If you are also wondering what JSON stands for it is: JavaScript Object Notation. Lastly if you are wondering if JWT has a pronunciation, it does, and it is pronounced "jit".

JWTs being tokens, unsurprisingly, use token-based authentication which is stateless. This means that no information about a logged in user is stored on the server. The client (browser) is doing the storing of the token. The client will send the token to any request that needs to be authenticated within the headers. The JWT is encoded, so when you are sending your user data with it, if it is intercepted by anyone shady it will be protected.

JWT Auth Flow

Alt Text
Photo Credit: Learn.co (https://i.stack.imgur.com/f2ZhM.png)

When a user signs in with a valid username and password (validated by the back end) the backend gives a signed token to the client. The client will store the token and it will be supplied in the headers to every request that needs authorization. Effectively, it is an access pass for the user that stores unique encoded identifiers and the unique signature from the backend. It proves the user is who they say they are.

JWT Format

JWTs are a singular object of three concatenated strings separated by a . A sample JWT would look something like this: aaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccccc

The first string (aaa...a) is the header which contains the algorithm used to encrypt it and the type of token which of course is JWT. The second string (bbb...b) is the payload which contains all the meat. It can contain what you want, but generally you'll include the user id and username etc. The third string (ccc...c) is the signature which contains a hash (encryption) of the header and the payload. It is hashed with a secret key that is provided by the developer.

If you are curious you can go to jwt.io and try this for yourself!

Environment Variables on Rails With Figaro Gem

The Figaro Gem is a helpful Ruby Gem that allows the developer to user environment variables. Environment variables are simply key value pairs that can be called within your app.

Upon installing the Figaro Gem it will create a file in your config folder called 'application.yml'. The 'application.yml' file will be in your '.gitignore'. This means that when you push your project to GitHub your 'application.yml' will not be visible. That way your secret key can not be seen by the public and you avoid a huge hole in your security.

Using the environment variables looks like this:

# config/application.yml
my_secret_key: "b1g_s3cr3t"

# And to access the environment variable we use this syntax
ENV["my_secret_key"]

And that's all I am covering, thanks for reading and I hope you learned something!

Top comments (0)