Skip to main content

Using JWT in Rails

JWT is a Json Web Token,It is a standard and has been implemented in almost all popular programming languages. Hence, they can be easily used or exchanged in systems implemented in diverse platforms.
JWT has libraries for almost all platforms and Ruby is no exception.
Now we will see how JWT is used in Rails:
We will create a simple Rails application which uses the excellent Devise gem for authentication and the jwt gem for creating and verifying JWT tokens.
Let’s create a sample Rails application :
rails new rails_on_jwt
Once the application is generated, create a Home controller which we will use to check our authentication.
Create  home_controller.rb in the app/controllers
classHomeController ApplicationController
 def index
 end
end
Write the route for  HomeController to /home in config/routes.rb:
Rails.application.routes.draw do
get 'home' => 'home#index'
end
Now, add Devise to our application. First, we will add the Devise and jwt gems in our Gemfile.
gem 'devise'
gem 'jwt'
Then run a command “bundle install” on terminal.
Now let’s create the Devise configuration files:
For that we have will have to create the Devise User model and migrate the database:
rails g devise User
rakedb:migrate
Created User Model use for authentication.now  It’s time to integrate jwt into our application. First, we will create a class named JsonWebToken in lib/json_web_token.rb.This class will encapsulate the JWT token encoding and decoding logic.
classJsonWebToken
defself.encode(payload)
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end

defself.decode(token)
returnHashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
rescue
nil
end
end
We have to create an initializer for including the JsonWebToken class in config/initializers/jwt.rb.
require 'json_web_token'
We have to add some helper method in ApplicationController class which we will use in AuthenticationController class:
In app/controllers/application_controller.rb:
classApplicationController
<ActionController::Base
attr_reader :current_user

protected
defauthenticate_request!
unlessuser_id_in_token?
renderjson: { errors: ['Not Authenticated'] }, status: :unauthorized
return
end
    @current_user = User.find(auth_token[:user_id])
rescue JWT::VerificationError, JWT::DecodeError
renderjson: { errors: ['Not Authenticated'] }, status: :unauthorized
end

private
defhttp_token
      @http_token ||= if request.headers['Authorization'].present?
request.headers['Authorization'].split(' ').last
end
end

defauth_token
    @auth_token ||= JsonWebToken.decode(http_token)
end

defuser_id_in_token?
http_token&&auth_token&&auth_token[:user_id].to_i
end
end 
We have added a few helper methods like authenticate_request!which will act as a before_filter to check user credentials and we have created AuthenticationController to handle all authentication requests to the API. In app/controllers/authentication_controller.rb:
classAuthenticationController<ApplicationController
defauthenticate_user
user = User.find_for_database_authentication(email: params[:email])
ifuser.valid_password?(params[:password])
renderjson: payload(user)
else
renderjson: {errors: ['Invalid Username/Password']}, status: :unauthorized
end
end
private
def payload(user)
return nil unless user and user.id
    {
auth_token: JsonWebToken.encode({user_id: user.id}),
user: {id: user.id, email: user.email}
    }
end
end
Here we have added AuthenticationController to implement the authentication endpoint. It uses Devise to authenticate the user and issue a JWT if the credentials are valid.
Now we have to update our routes.rb to add the authentication endpoint.
Rails.application.routes.draw do
post 'auth_user' => 'authentication#authenticate_user'
get 'home' => 'home#index'
end
Also, we have to modify the HomeController to secure it using a before_filter and add a meaningful response in case of successful authentication:
classHomeController<ApplicationController
before_filter :authenticate_request!
def index
renderjson: {'logged_in' => true}
 end
end
Now, create a sample user to test the authentication by using rails console or by Using Seed command:Start the server and check out how JWT authentication works:
rails s
Source: http://www.cryptextechnologies.com/blogs/using-jwt-in-rails 

Comments

Popular posts from this blog

GraphQL With Ruby

Now a day’s most of the web or mobile applications fetch data from server which is stored in a database. REST API provides an interface to stored data that require by the applications. GraphQL is a query language for REST API's not for server databases. It is database agnostic and effectively can be used in any context where an API is used. GraphQL provide platform for declarative data fetching where client need to specify what data needs from API in response. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for. GraphQL minimizes the amount of data that needs to be transferred over the network and improves applications operating under these conditions. Introduction to GraphQL API on Ruby on Rails Start with adding gem in Gemfile gem ‘graphql’ Run command bundle install Run command rails generate graphql:install Above command will add gr

Best In Place Gem In Ruby On Rails Tutorial

The best_in_place gem is the easiest solution for in place editing in Ruby on Rails. This gem provides functionality of “in place editing” in ruby on rails without writing any extra ajax code. It supports text inputs, textarea, select dropdown, checkboxes, jQuery UI Datepickers, etc. Also Displays server-side validation Installation Steps of “best_in_place” Gem : Installing best_in_place is very easy and straight-forward. Just begin including the gem in your Gemfile: gem ‘best_in_place’ After that, specify the use of the jquery and best in place javascripts in your application.js, and optionally specify jquery-ui if you want to use jQuery UI datepickers: //= require jquery //= require best_in_place //= require jquery-ui //= require best_in_place.jquery-ui Then, just add a binding to prepare all best in place fields when the document is ready: $(document).ready(function() { /* Activating Best In Place */ jQuery(".best_in_place").best_in_place(); });

Data scraping in Ruby on Rails using Nokogiri and Mechanize Gem

What is Data scraping? Website/Data  Scraping  is a technique to operating large amounts of  data  from websites whereby the  data  is extracted and displayed in own sites or it can be stored to a File/Database. Data scraping is basically used where the websites does not provides API. Some Applications do not provide API to collect records. For the same , Data Scraping technique is used. The data can be scraped using Nokogiri Gem. The steps are required: Add the gem “gem ‘nokogiri’, ‘~> 1.8’, ‘>= 1.8.1'” . Then run the bundle install Add the “require ‘nokogiri'” , “require ‘open-uri'” line where you will write the code for the scraping. The controller of the page will look like below: The view of the code of view page will look like : The result in our application will look like: Mechanize Gem in rails The Mechanize library is used for automating interaction with websites. Mechanize automatically stores and sends cookies, follo