Angular 2+ and Ruby on Rails user authentication

How to setup an Angular 2+ frontend with User Register/Login capabilities using Ruby on Rails backend and Devise Token Auth gem

Intro

Final result

Prerequisites

Angular features we’ll use

Part 1: Backend

Rough plan

Setup

$ rails new rails_devise_token_auth --api --database=postgresql
gem 'devise_token_auth'
gem 'omniauth'
gem 'rack-cors', :require => 'rack/cors'
$ bundle install 
Rails.application.config.middleware.use Rack::Cors do  allow do    origins '*'    resource '*',    :headers => :any,    :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],    :methods => [:get, :post, :options, :delete, :put]  endend

Database configuration

default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: rails_devise_token_seed_development
username: YOUR_CUSTOM_USERNAME
password: YOUR_PASSWORD
test:
<<: *default
database: rails_devise_token_seed_test
username: YOUR_CUSTOM_USERNAME
password: YOUR_PASSWORD

Create the database

$ rails db:create

Initialise Devise User Model

$ rails generate devise_token_auth:install User auth
create  config/initializers/devise_token_auth.rbcreate  db/migrate/20170131161242_devise_token_auth_create_users.rbcreate  app/models/user.rbinsert  app/controllers/application_controller.rbgsub  config/routes.rb

Configure User Model

class User < ActiveRecord::Base


devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:trackable,
:validatable,
:omniauthable
include DeviseTokenAuth::Concerns::Userend

Create a default User seed

User.create(email: 'user@example.com', nickname: 'UOne', name: 'User One', password: "monkey67")

Migrate and Seed the DB

rails db:migrate && rails db:seed

Test the API

$ rails s
Response body
Response headers
curl -v -X "POST" "http://localhost:3000/auth/sign_in" \
-H "Content-Type: application/json; charset=utf-8" \
-d $'{
"email": "user@example.com",
"password": "monkey67"
}'

Click here for the Part 2: Setting up Angular frontend

Research & Development engineer at IRCAD — IHU. Mobile & Web Engineering.