mhanberg

mhanberg

Expert LSP Core Team

Implementing API Authentication with Guardian in Phoenix

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!

First Post! Switch mode

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)

Most Liked

mhanberg

mhanberg

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:

mhanberg

mhanberg

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/

Last Post!

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

Where Next?

Trending in Guides/Tuts Top

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement