mhanberg

mhanberg

Expert LSP Core Team

Hi! I recently finished adding authentication to my Phoenix API, so I wanted to share what I learned.

I haven’t created authentication for an API only application before, so not using sessions/cookies was a little confusing at first. I hope this post can help others who haven’t writter an API before!

Thanks!

Showing Posts 1 to 9

acrolink

acrolink

@mhanberg, thank you very much. I want to ask, for how long is the token valid? How to configure that setting and does the token refresh / extends its validity the user actively is using it (i.e. does it expire only if it had been idle for some time)

mhanberg

mhanberg OP

Expert LSP Core Team

The documentation for the configuration you’re looking for is here GitHub - ueberauth/guardian: Elixir Authentication · GitHub. These options go in the configuration in config.ex

The default TTL (time to live) for the JWT is 4 weeks and I believe you need to manually refresh the token. My post doesn’t detail that aspect :sweat_smile:

acrolink

acrolink

Would you elaborate this piece of code, how to handle email errors here (email not found or wrong password), i.e. how to return 401 if email not found or credentials are wrong, here:

def sign_in(conn, params) do
  # Find the user in the database based on the credentials sent with the request
  with %User{} = user <- Accounts.find(params.email) do
    # Attempt to authenticate the user
    with {:ok, token, _claims} <- Accounts.authenticate(%{user: user, password: login_cred.password}) do
      # Render the token
      render conn, "token.json", token: token
    end
  end
end
mhanberg

mhanberg OP

Expert LSP Core Team

I’m on a business trip right now, I’ll reply to this when I get some free
time. But in the meantime, look into the Phoenix Fallback Controller
functionality.

Relevant blog →

https://swanros.com/2017/03/04/action-fallback-contexts-phoenix1-3-tiny-controllers/amp/

acrolink

acrolink

I have managed to put this code together:

defmodule AcrosapWeb.FallbackController do
  @moduledoc """
  Translates controller action results into valid `Plug.Conn` responses.
  See `Phoenix.Controller.action_fallback/1` for more details.
  """

  use AcrosapWeb, :controller

  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    conn
    |> put_status(:unprocessable_entity)
    |> render(AcrosapWeb.ChangesetView, "error.json", changeset: changeset)
  end

  def call(conn, {:error, :not_found}) do
    conn
    |> put_status(:not_found)
    |> render(AcrosapWeb.ErrorView, :"404")
  end

  def call(conn, {:error, :unauthorized}) do
    conn
    |> put_status(:forbidden)
    |> json(%{status: "forbidden"})
  end


end

it is working except at the situation that the user object cannot be found by his email address, I get this error:

(FunctionClauseError) no function clause matching in AcrosapWeb.FallbackController.call/2

mhanberg

mhanberg OP

Expert LSP Core Team

I would take a look at the return value of the call you’re making in the with expression.

kokolegorille

kokolegorille

To get rid of this error message, You can add something like this

  def call(conn, args) do
    IO.inspect args
    conn
    |> put_status(:whatever)
    |> json(%{status: "whatever"})
  end
acrolink

acrolink

Thanks @kokolegorille, based on your idea I have found that the code block needed to handle wrong email address (non existent in DB) is:

def call(conn, :nil) do
  conn
  |> put_status(:unauthorized)
  |> json(%{status: "unauthorized"})
end
— All posts loaded —

Where Next? Top

Trending in Guides/Tuts Top

rogach
I’ve spent some time understanding how to do hot code reloading with releases built using mix release, and here I’d like to detail the st...
New
c4lliope
# ~/src/livebook/.iex.exs System.cmd("xdg-open", [ LivebookWeb.Endpoint.access_url() ] ) Because Livebook requires a unique passcode on ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews