10
votes
How to use devise gem for authentication in API-only Rails application - Stack Overflow
Asked
Active 4 days ago
Viewed 23k times
10

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?

2
14

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.

2
  • 4
    Note that knock doesn’t support OAuth, and devise_token_auth requires cookies to work. Jun 13 2017 at 4:08
  • 2
    speaking of JWT (and devise): This article was very helpful for me Stop using JWT for sessions. I'm still using Rails Session Cookies for API Authentication
    – Pascal
    Nov 7 2018 at 11:39
1

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

    Not the answer you're looking for? Browse other questions tagged or ask your own question.

     
    2
    go through devise token base authentication github.com/lynndylanhurley/devise_token_auth - Pardeep Dhingra
    Thank You Pardeep Dhingra it worked - user2918410

    2 Answers

    14
    votes

    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.

    1
    votes

    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