Screencast
Combining Guardian with Phx Gen Auth
24. Combining Guardian with Phx Gen Auth
Add JWT Authentication to Phoenix User Sessions
When building a Phoenix application with both web and API interfaces, you often need to support different authentication methods. While Phoenix's built-in authentication works great for web sessions, APIs typically require token-based authentication. Here's how to combine them using Guardian, allowing users to authenticate with the same credentials regardless of interface.
defmodule Tutorial.Users.Guardian do
use Guardian, otp_app: :tutorial
def subject_for_token(user, _claims) do
{:ok, %{user_id: to_string(user.id)}}
end
def resource_from_claims(%{"sub" => %{"user_id" => user_id}}) do
user = Users.get_user!(user_id)
{:ok, %{user: user}}
end
end
Secure Phoenix API Endpoints with JWT Authentication
Protecting API endpoints with JWT authentication in Phoenix is straightforward once you have the basic setup in place. Guardian provides pre-built plugs that handle token verification and user loading, making it easy to secure specific routes or entire API sections.
defmodule TutorialWeb.Api.AuthAccessPipeline do
use Guardian.Plug.Pipeline, otp_app: :tutorial
plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}
plug Guardian.Plug.EnsureAuthenticated
plug Guardian.Plug.LoadResource, allow_blank: true
end
Implement JWT Token Generation for API Authentication
When a user authenticates successfully with their email and password, you'll want to generate a JWT token they can use for subsequent API requests. This process reuses the existing Phoenix authentication while adding the token generation step.
def create(conn, %{"email" => email, "password" => password}) do
case Users.get_user_by_email_and_password(email, password) do
%User{} = user ->
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user)
conn
|> put_status(:created)
|> render(:create, user: user, jwt: jwt)
nil ->
# Handle authentication failure
end
end
What you'll learn in this video:
- How to set up Guardian for JWT authentication alongside Phoenix's built-in authentication
- Techniques for securing API endpoints with JWT verification
- Best practices for implementing token-based authentication in Phoenix
- How to handle authentication errors and provide meaningful responses
- Strategies for managing user sessions across web and API interfaces
- Ways to customize JWT claims and handle token verification