Yama

Yama

Gaining an understanding of Session Cookies and JWT Token

Thanks for stopping by. For a brief context, I’m currently create a ecommerce side project for my wife which may (most likely) use PayPal API for when dealing with purchases. Now here is the tech question I’m trying to better understand. Please correct me if I’m wrong with some things.

Session Cookies - This is something that we can create locally. One form is by using Phoenix put_session and save the information we may need in the future like a user ID and we can remove/delete the information after the user logs out is my understanding. This will help keep the user logged in.

JWT Token - This one confuses me. From my understanding we will parse the information from the header (HTTP request). Although what I don’t understand is while I implemented a context file and guardian file that suppose to check and insert a current_user, it is always failing since in routes, it runs before we hit any controllers. I learned it is because we need to send a Bearer and token to authenticate the user. But the part that confuses me is, if we need to send this information, how is this information being send from the frontend when making a http request?

Session Steps -
1 - hit end point login_user
2 - check if the user is valid
3 - if true save to the session cookie
4 - logout endpoint
5 - remove current_user from session cookie

JWT Token -
0 - Check if current_user exist
1 - hit end point login_user
2 - check the header token if present
3.1 - Not present returns %{}
3.2 - Present then check if user is valid by checking password and saved password_hash
4 - return {user: user, token: JWT_Token}

From the steps what I don’t get is when does current_user get placed in a session through JWT token? and how are we sending authorization/token to the backend when lets say my React project does an axios request of post with user information? One solution I noticed some people say is save to the DB the token but also seen people say that is a bad idea.

Thanks for the clarity on these concepts.

Most Liked

victorolinasc

victorolinasc

This is a wide topic. Session Cookies and JWT tokens are not the same thing and though when we compare them only by their names we are not comparing the same thing.

Using session cookies for authentication is a good use case scenario of cookies if your backend server is a monolith or if you have some kind of API gateway that keeps and translates cookies into user_ids for other services and you are not using something like zero-trust network.

JWTs are more of a tool than a user authentication solution. It comes in 2 flavors: signed tokens (JWS) and encrypted tokens (JWE). Both have their use cases that almost always fall on the category of distributed trust, like all your servers need to verify the authenticity of a token and you won’t share a global cookie store because you would need to also share the cookie signing keys and so on.

So, in my personal opinion, use what makes more sense to you. If it is a simple single server just use a cookie session and you’re good. Remember to make your cookies https only (to avoid JS accessing those) and you should be fine.

When the time comes for a more complex authentication/authorization solution, look for different approaches. One of them might be JWTs which might be persisted but make sure to research first.

To answer one of your questions, the traditional way of passing authentication data in the standard HTTP specification is to use the reserved header name authorization. The value starts with the name of the authentication scheme (something like “Basic”, “Digest” or “Bearer”) and the value of it. See here for a better explanation.

When you use cookies, the frontend also sends them through headers, in this case, the COOKIE, header. See here again for a better explanation.

@wolfiton be careful when storing tokens on local storage! It is not best practice when dealing with tokens on the frontend. See here for reference.

victorolinasc

victorolinasc

The subject is very broad… I’ve explained before why I think JWTs are useful here and why they don’t necessarily compare to session cookies.

Just so people don’t get it wrong, OWASP has a dedicated session on JWT (using Java) and considerations one should take into account when using it for authentication (it is here). It also has many considerations for all other kinds of authentication. Even cookie based session management.

At the same time it advocates the use of OpenID Connect as a widely adopted specification for identity providers and that protocol uses JWTs a lot. As do OAuth. They are not meant for your use case. Your architecture is a very simple web app that a session cookie might be enough.

In any case, I think that associating JWTs with an authentication system is not correct. I think it is a tool that has use cases as diverse as ensuring a signing and encryption set of algorithms implemented in a wide variety of languages in a variety of libraries.

But just to reiterate: your use case is simple and an HTTP session cookie with any opaque id (shouldn’t be guessable by the frontend) with httpOnly flag set is good enough security (nothing is 100% safe anyway). For other cases with distributed services that won’t be enough in my humble opinion. Nonetheless, you shouldn’t start with an OAuth/OpenID server if you don’t really know you are going to need it.

wolfiton

wolfiton

Here is that function used in the plugs to set the context of absinthe medium_graphql_api/lib/medium_graphql_api_web/plugs/context.ex at develop · wolfiton/medium_graphql_api · GitHub

To get a better understanding on how this all works clone the repo and try to play with it.

Use the playground in graphiql to create and login users.

I also new to phoenix elixir and vue, maybe this tut could help you get a better idea of the whole project it was the inspiration for my current project https://www.youtube.com/watch?v=uoCFQu9gQHE&list=PLw7bfDlTRWbgiApK7X1bRKJJ03xoDU3hm

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement