Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use devise gem for authentication in API-only Rails application

I want to create a rails API with the devise gem for authentication. I am using Chrome Postman to check API outputs.

My environments:

  • Rails 4.2
  • Ruby 2.3

What I did:

  1. ran

    rails new my_api
    cd my_api
    
  2. added devise gem in Gemfile

  3. bundle install
  4. added

    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
    

    to environment/development.rb

  5. created one user using rails console

After that I tried to login from postman. I gave email and password into headers of postman.

POST  http://localhost:3000/users/sign_in

headers

email abcd@gamilcom

password abcd1234

but it's not authenticating. What do I need to do?

like image 741
user2918410 Avatar asked Mar 04 '16 12:03

user2918410


People also ask

How does API authentication work in Rails?

The user enters his details and sends the request to the server. If the information is correct, the server creates a unique HMACSHA256 encoded token, also known as the JSON (JWT) web token. The client maintains JWT and executes all the following requests on the server with the attached token.


2 Answers

You may want to use knock or devise_token_auth in an API context. Be carreful, your email seems to be invalid. I don't know Postman but the POST parameters should live in the body of your HTTP request.

like image 159
rdupz Avatar answered Oct 13 '22 00:10

rdupz


HTTP Basic Auth is turned off by default on Devise. It is simple to enable it and for most API purposes, basic auth is sufficient.

You need to do two things to enable HTTP basic auth:

  • :database_authenticatable strategy in your user/account model
  • config.http_authenticatable = true in the devise initializer

See more here: https://github.com/plataformatec/devise/wiki/How-To:-Use-HTTP-Basic-Authentication

like image 29
Dagmar Avatar answered Oct 12 '22 23:10

Dagmar