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

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
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

We're in Beta

About us Mission Statement