Generate the Authentication Layer

Learn how to use generators and develop authentication layer for user identification.

In the following lessons, we’ll learn how to use the generator to build an authentication layer, we’ll see how the pieces of generated code fit together to handle the responsibilities of authentication, and we’ll even see how LiveView uses the authentication service to identify and operate on the logged-in user.

What is phx.gen.auth?

To build a well-structured authentication layer for Phoenix requests, we can use the phx.gen.auth application generator. This generator is rapidly becoming the authentication standard for all Phoenix applications. Though phx.gen.auth is not a LiveView framework, all LiveViews begin as standard web requests. That means a plug-based approach suits our purposes just fine to authenticate our users in LiveView, as well as throughout the rest of our application. Using this generator, we’ll be able to generate, rather than hand-roll, a solution that’s mostly complete, and adapt it to meet any further requirements we might have.

We’ll start by installing and running the generator.

Adding the dependency

To use this authentication generator, we need to add phx_gen_auth to our application’s dependency list. To do so, we navigat to the pento/mix.exs and added the phx_gen_auth library like this:

Get hands-on with 1200+ tech skills courses.