How to Transition from Joken 1.5 to 2.0

Hello everyone!
Is there anybody who has experience using Joken 2.0?
I am trying to migrate the following code (v1.5.1) to (v2.0)
The API has changed quite significantly can’t seem to follow thru it
Would love to hear your feedback…
views/session_view.ex

defmodule LibraryApiWeb.SessionView do
  use LibraryApiWeb, :view

  def render("token.json", user) do
    data = %{id: user.id, email: user.email, username: user.username}

    jwt = %{data: data, sub: user.id}
    |> Joken.token
    |> Joken.with_signer(Joken.hs512("SOMESECRETVALUE"))
    |> Joken.sign

    %{token: jwt.token}
  end
end

I tried the following:

defmodule LibraryApiWeb.SessionView do
  use LibraryApiWeb, :view

  def render("token.json", user) do
    data = %{id: user.id, email: user.email, username: user.username}

    jwt = %{data: data, sub: user.id}
    |> LibraryApi.Token.generate_and_sign(Joken.Signer.create("HS512", "SOMESECRETVALUE"))

    %{token: jwt.token}
  end
end

But I am getting the following in Postman

{
    "errors": [
        {
            "detail": "Error logging in a user with that email and password",
            "status": 401,
            "title": "Unauthorized"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}

despite that email being in the database already

Hey I know it’s been quite some time, but I’m running through (what I presume is) the same tutorial now and I had found a solution and wanted to document it for others who may be struggling with the same transition.

In order to switch to Joken 2 (or 2.1.0 as I am) you first need to create a Token module, so create a new file called token.ex in /lib, within the file you’ll need to define your module to use Joken:

defmodule Token do
  use Joken.Config

  def token_config do
    default_claims()
  end
end

Next, in your session view, you’ll want to define an explicit signer and generate your token, before passing it back to the view:

defmodule LibraryApiWeb.SessionView do
  use LibraryApiWeb, :view

  def render("token.json", user) do
    data = %{id: user.id, email: user.email, username: user.username}

    jwt = %{data: data, sub: user.id}
    signer = Joken.Signer.create("HS512", "SOMESECRETVALUE")
    token = Token.generate_and_sign!(jwt, signer)
    %{token: token}
  end
end

And then you should be able to verify your token on jwt.io as instructed

4 Likes

I noticed that there is an official upgrading from 1.x to 2.x guide so I’m going to post a link to it here: https://github.com/joken-elixir/joken/blob/master/guides/migration_from_1.md

2 Likes