micahsoftdotexe

micahsoftdotexe

Guardian Refresh Token In Cookie Pipeline

Greetings,
I am attempting to implement a jwt pattern in phoenix using guardian. What I am doing is that I am returning a short lived access token in the response and a long lived refresh token in the cookies. So far, I am able to send back a token back in a cookie using the following code:

with({:ok, jwt, _full_claims} <- Token.encode_and_sign(user, %{}, ttl: {1, :minute}),
      {:ok, cookieJWT, _full_claims} <- Token.encode_and_sign(user, %{}, [ttl: {1, :week}, type: :refresh])) do
        conn
        |> put_resp_cookie("refresh_token", cookieJWT, http_only: true)
        |> put_resp_content_type("application/json")
        |> send_resp(200, Jason.encode!(%{token: jwt}))

and I am trying to create a refresh method and guarding it with a pipeline that looks like the following:

plug Guardian.Plug.VerifySession, [refresh_from_cookie: true, key: "refresh_token"]
  plug Guardian.Plug.EnsureAuthenticated
  plug Guardian.Plug.LoadResource

The issue is that VerifySession does not appear to be able to verify the cookie (even though it appears to be sent) because EnsureAuthenticated returns an error. Is there something that I am doing wrong? I am pretty new to Phoenix and Elixir in general so any help would be greatly appreciated.

Marked As Solved

micahsoftdotexe

micahsoftdotexe

I was able to craft my own plug that is able to both grab the correct token and verifies it with the following:

defmodule MyApp.Auth.CookieTokenValidator do
  import Plug.Conn
  alias Guardian.Plug.Pipeline

  @behaviour Plug
  @impl Plug
  def init(opts), do: opts
  @impl Plug
  def call(conn, opts) do
    with {:ok, token} <- get_token_from_cookie(conn, opts),
    module <- Pipeline.fetch_module!(conn, opts),
    {:ok, claims} <- Guardian.decode_and_verify(module, token, %{}, opts) do
      conn
        |> Guardian.Plug.put_current_token(token, key: "default")
        |> Guardian.Plug.put_current_claims(claims, key: "default")
    else
     _error -> conn
      |> send_resp(401, Jason.encode!("Could not validate token"))
      |> halt()
    end
  end

  defp get_token_from_cookie(conn, opts) do
    key = Keyword.get(opts, :key, "token")
    token = conn.req_cookies[key]
    if token, do: {:ok, token}, else: :no_token_found
  end
end

but I would like to find the proper way to do it.

Also Liked

micahsoftdotexe

micahsoftdotexe

It returns the error of unauthenticated as a response (with a 401).

muelthe

muelthe

I had been working through an issue mself (hence the original question). I have a very simple setup (almost identical to the docs in conjunction with Ueberauth for an msoauth setup) and the problem for me was misconfiguration of the endpoint, specifically the SameSite config.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
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
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
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

We're in Beta

About us Mission Statement