Getting Started With Rails Devise Token Auth
Tags: beginners, rails, tutorial, ruby
Published: 2023-02-05 04:23:27

## Introduction

Hello! 👋 
Recently I had to use Rails devise_token_auth at work, so for my future self, and hopefully you the reader. I will show you how you can implement this easily. 😃

First we need to actually create the project.

---

## Initializing The Project

Creating a new project is easy with the rails command:

```
rails new devise_auth_token
```

Once the command is finished, enter your newly created project and open up the "Gemfile" and enter the following two gems required:

```txt
gem "devise"
gem "devise_token_auth"
```

Save the file and then run the following command to install both of the gems:

```bash
bundle install
```

Next we will also need to install both of the gems, this can be done via the following commands:

```bash
rails g devise:install
rails g devise_token_auth:install User auth
```

Finally we need to migrate the database, which can be done via:

```bash
rails db:migrate
```

Done! 😆 Next we need to configure the devise plugins.

---

## Configuring Devise 

Now that we have installed devise we next need to change some of the settings.

Open up config/initializers/devise_token_auth.rb and add the following oneline:

```ruby
config.change_headers_on_each_request = false
```

If you want the headers to change after every request set the above to "true", for testing purposes I have changed it to false but you may want to change the headers on each request for added security.

Next open up app/controllers/application_controller.rb and add the following:

```ruby
protect_from_forgery unless: -> { request.format.json? }
```

Since we don't use sessions and use our own tokens we don't really need forgery protection. But I recommend you don't set the above if you plan on session management.

Next create a new Controller to test out authentication, this can be done with the following command:

```bash
rails g controller game
```

This should create a new "GameController", open up the new GameController and add the following:

```ruby
class GameController < ApplicationController
  before_action :authenticate_user!

  def index
    render :nothing => true, :status => :ok 
  end 
end
```

Adding "authenticate_user!" means the user will need to actually sign in before accessing the contents.

Next create a new directory "app/views/game", and create new "index.html.erb" file with the following contents:

```html
<h1>Hello</h1>
```

Simple I know. Next we need to configure the route to access this which can be done by adding the following to "config/routes.rb":

```ruby
resources :game, only: [:index]
```

Make sure to include the only as if left it rails we add a bunch of redeundent routes to your project, which is not desired.

Done! Now we can finally test it out! 😎

---

## Testing The Implementation

Finally we get to test the implementation! 😄

The following command allows you to register a user:

```bash
curl localhost:3000/auth -X POST -d '{"email": "example@example.com", "password": "password", "password_confirmation": "password"}' -H "content-type:application/json"
```

The next command allows you to sign in as a user and will give you the authentication headers.

```bash
curl localhost:3000/auth/sign_in -i -X POST -d '{"email": "example@example.com", "password": "password"}' -H "content-type:application/json"
```

Finally we can access the Game view via the following command: (Please note the headers will be deferent)

```bash
curl localhost:3000/game -H "access-token: rvb5ZQTOu8QNv7K9cSGSdA" -H "client: RkgM3tLEWiUOcfwrJWiCSg" -H "uid: example@example.com"
```

The response should give the HTML file. Also if you change any of the headers to something incorrect you should get a 401 please sign in response. 😸

Feel free to use this in your project.

---

## Conclusion

Here I have shown how you can implement devise token auth into a new Rails project. 
It was a lot easier than I expected, but I decided to write it down for future me and hopefully this post has helped you. 😺

As always you can find the sample code at my Github:
https://github.com/ethand91/Rails-Devise-Auth-Sample

---

Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee. 

[![“Buy Me A Coffee”](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/ethand9999)

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the [following course](https://algolab.so/p/algorithms-and-data-structure-video-course?affcode=1413380_bzrepgch)