Adding Authentication to a Phoenix Application
Creating a New Phoenix Application
To add authentication to a Phoenix application, we’ll start by creating a new Phoenix application and updating the dependencies. Run the following command in your terminal:
mix phx.new my_app
cd my_app
mix deps.get
Generating Authentication Files
Next, we’ll use the phx.gen.auth
generator to create the necessary files and update the existing ones. Run the following command:
mix phx.gen.auth Users User users
This will generate the necessary files for user authentication, including controllers, views, and templates.
Configuring the Database
Update the database credentials in config/dev.exs
to reflect the changes made by the phx.gen.auth
generator:
config :my_app, MyApp.Repo,
username: "postgres",
password: "postgres",
database: "my_app_dev",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10
Then, run the following command to migrate the database:
mix ecto.migrate
Protecting Routes
To add authentication to our routes, we’ll put them behind the :require_authenticated_user
plug. Update the router.ex
file as follows:
defmodule MyApp.Router do
use MyApp.Web, :router
import Plug.Conn
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :protected do
plug :require_authenticated_user
end
scope "/", MyApp do
pipe_through [:browser, :protected]
get "/", PageController, :index
# Add more protected routes here
end
scope "/", MyApp do
pipe_through [:browser]
get "/users/register", UserController, :new
post "/users/register", UserController, :create
get "/users/login", UserController, :new
post "/users/login", UserController, :create
get "/users/logout", UserController, :delete
end
end
Testing Authentication
Finally, we can test the authentication by logging out of the application and trying to access the protected routes. If everything is set up correctly, you should be redirected to the login page when trying to access a protected route.
- Start the Phoenix server:
mix phx.server
- Open a web browser and navigate to http://localhost:4000/
- Try to access a protected route, such as http://localhost:4000/admin
- You should be redirected to the login page
- Login with a valid user credentials
- Try to access the protected route again
- You should now have access to the protected route