user2918410
user2918410

Reputation: 119

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:

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?

Upvotes: 12

Views: 25255

Answers (2)

Dagmar
Dagmar

Reputation: 3281

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

Upvotes: 1

rdupz
rdupz

Reputation: 2313

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.

Upvotes: 14

Related Questions