User Authentication in Rails API

Wajeeh Ahsan
1 min readJan 31, 2020

--

You can use rails to develop a complete web app (frontent + backend) or just API (only backend). If you’re working with rails to develop and rest API and you need to perform user authentication with devise, this tutorial is heplful for this.

Prerequisite
You’re supposed to be done with this part. If you’re working with api-based rails app, you need to authenticate user on your own. To do this, follow this tutorial.

Suppose ApplicationController is the file which is acting as a devise user authentication. If you don’t know which controller is doing the job, look for this line of code:

acts_as_token_authentication_handler_for ModelName

Now jump into this file, place following lnes of code:

privatedef authenticate_user_from_token! user_email = request.headers["HTTP_EMAIL"].presence user = user_email && User.where(email: user_email).first if user && Devise.secure_compare(user.authentication_token,   request.headers["HTTP_AUTHENTICATION_TOKEN"])   sign_in user, store: false else   render_unauthorized("Unauthorized user or incorrect authentication token") endenddef render_unauthorized(message) errors = { errors: [ { detail: message } ] } render json: errors, status: :unauthorized
end

Now you can call this method anywhere in your app’s controller. Suppose I want to authenticate the user accessing any action inside my ProjectController.rb. For this purpose, I’ll place following line of code in this controller file:

before_action :authenticate_user_from_token!

making it sure that this controller inherits from Application_Controller.rb like this:

ProjectsController < ApplicationController

Finally, look at the authenticate_user_from_token function implementation. It requires you to pass email and authentication_token in headers when you hit this API from Postman.
All DONE!

--

--

Wajeeh Ahsan
Wajeeh Ahsan

No responses yet