> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Login to Your Ruby on Rails Application

> This tutorial demonstrates how to add user login to a Ruby on Rails application.

[View On GitHub](https://github.com/auth0-samples/auth0-rubyonrails-sample/tree/master/sample)

Download Sample

###

To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is
where you will configure how you want authentication to work for the project you are developing.

### Configure an application

Use the interactive selector to create a new Auth0 application or select an existing application that represents
the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID
that your application code will use to call Auth0 APIs through the SDK.

Any settings you configure using this quickstart will automatically update for your Application in the [Dashboard](https://manage.auth0.com/#/), which is where you
can manage your Applications in the future.

If you would rather explore a complete configuration, you can view a sample application instead.

### Configure Callback URLs

A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have
authenticated. If not set, users will not be returned to your application after they log in.

> [!NOTE]
>
> If you are following along with our sample project, set this to
> `http://localhost:3000/auth/auth0/callback`.

### Configure Logout URLs

A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged
out. If not set, users will not be able to log out from your application and will receive an error.

> [!NOTE]
>
> If you are following along with our sample project, set this to `http://localhost:3000`.

### Configure Allowed Web Origins

An Allowed Web Origin is a URL that you want to be allowed to access to your authentication flow. This must
contain the URL of your project. If not properly set, your project will be unable to silently refresh
authentication tokens, so your users will be logged out the next time they visit your application or refresh a
page.

> [!NOTE]
>
> If you are following along with our sample project, set this to `http://localhost:3000`.

###

Use `omniauth-auth0`, a custom [OmniAuth strategy](https://github.com/intridea/omniauth#omniauth-standardized-multi-provider-authentication), to handle the authentication flow.

Add the following dependencies to your `Gemfile`:

```gem lines theme={null}
gem 'omniauth-auth0', '~> 3.0'
gem 'omniauth-rails_csrf_protection', '~> 1.0' # prevents forged authentication requests
```

Once your gems are added, install the gems with `bundle install`.

###

Create a configuration file `./config/auth0.yml` to specify your Auth0 domain, client ID, and client
secret values located in your Auth0 Dashboard under application **Settings**.

###

Create the following initializer file `./config/initializers/auth0.rb` and [configure](https://github.com/auth0/omniauth-auth0/blob/master/EXAMPLES.md#send-additional-authentication-parameters) the **OmniAuth** middleware with the configuration
file you created in the previous step.

Ensure that `callback_path` matches the value given in the "Allowed Callback URLs" setting in your
Auth0 application.

###

Create an Auth0 controller to handle the authentication callback, `logout` action, and methods for
constructing the logout URL.

Run the command:
`rails generate controller auth0 callback failure logout --skip-assets --skip-helper --skip-routes --skip-template-engine`.

Inside the callback method, assign the hash of user information - returned as
`request.env['omniauth.auth']` - to the active session.

To configure logout, clear all the objects stored within the session by calling the `reset_session`
method within the `logout` action. Then, redirect to the Auth0 logout endpoint. To learn more about
`reset_session`, read [Ruby on Rails ActionController documentation](http://api.rubyonrails.org/classes/ActionController/Base.html#M000668).

###

Add these routes to your `./config/routes.rb` file.

Routes must be in place so Rails knows how to route the various Auth0 callback URLs to the Auth0 controller you
created in the previous step.

> [!NOTE]
>
> ##### Checkpoint
>
> Run your application to verify it continues to work as intended and you aren't receive any errors
> relating to Auth0.

###

A user can now log into your application by visiting the `/auth/auth0` endpoint.

> [!WARNING]
>
> To [prevent forged authentication requests](https://github.com/cookpad/omniauth-rails_csrf_protection), use the `link_to` or
> `button_to` helper methods with the `:post` method.

```ruby lines theme={null}
<!-- Place a login button anywhere on your application -->
<%= button_to 'Login', '/auth/auth0', method: :post %>
```

> [!NOTE]
>
> ##### Checkpoint
>
> Add a button to your application that redirects the user to the `/auth/auth0` endpoint when
> selected. Observe that you redirect to Auth0 to log in, and then back to your app after successful
> authentication.

###

Now that you can log in to your Rails application, you need a
way to log out. Log out a user by redirecting to the `auth/logout` action, which redirects them
to the Auth0 logout endpoint.

> [!NOTE]
>
> To test this after the previous step, you may need to clear out your session and then redirect the user
> to the Auth0 logout endpoint.

```ruby lines theme={null}
<!-- Place a logout button anywhere on your application -->
<%= button_to 'Logout', 'auth/logout', method: :get %>
```

> [!NOTE]
>
> ##### Checkpoint
>
> Add a button to your application that redirects the user to the `/auth/logout` endpoint when
> selected. Verify that you redirect to Auth0 and then quickly back to your application, and that you are no
> longer logged in.

###

To display the user's profile, your application should provide a protected route. You can use a [Concern](https://guides.rubyonrails.org/getting_started.html#using-concerns) to control access to routes that can be shared across multiple
controllers. The concern should automatically redirect to Auth0 when the user is unauthenticated. Otherwise, the
concern should return the current user profile.

Once you have a Concern, include it in any controller that requires a logged-in user. You can then access the
user from the session `session[:userinfo]` as in the following example:

```ruby lines theme={null}
class DashboardController < ApplicationController
include Secured
def show
@user = session[:userinfo]

end
end
```

Once the user loads from the session, use it to display information in your frontend:

```html lines theme={null}
<div>
<p>Normalized User Profile:<%= JSON.pretty_generate(@user[:info])%></p>
<p>Full User Profile:<%= JSON.pretty_generate(@user[:extra][:raw_info])%></p>
</div>
```

> [!NOTE]
>
> ##### Checkpoint
>
> Add the `Secured` concern to your app and then include it in the controller that requires an
> authenticated user to access it. Verify that an authenticated user has access to actions within that
> controller and that unauthenticated users are redirected to Auth0 for authentication.

## Next Steps

Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.

This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

* [Auth0 Dashboard](https://manage.auth0.com/dashboard/us/dev-gja8kxz4ndtex3rq) - Learn how to configure and manage your Auth0 tenant and applications
* [omniauth-auth0 SDK](https://github.com/auth0/omniauth-auth0) - Explore the SDK used in this tutorial more fully
* [Auth0 Marketplace](https://marketplace.auth0.com/) - Discover integrations you can enable to extend Auth0’s functionality
