Using Devise 1.3 to authenticate JSON login requests

前端 未结 3 2161
清歌不尽
清歌不尽 2020-12-09 22:44

I am new to rails. I am trying to write an API for a mobile application which authenticates using JSON. I want to use Devise for the authentication. I believe Devise >1.3 ad

3条回答
  •  抹茶落季
    2020-12-09 23:30

    I couldn't get to the linked page in the top answer so I thought I would add my own. You don't need to create any custom controllers. All you need to do is the following:

    In your application.rb add the following in your application class

    config.to_prepare do
      DeviseController.respond_to :html, :json
    end
    

    In config/initializers/devise.rb add :json to the formats. This line is commented out by default so you will need to uncomment the line.

    config.navigational_formats = ['*/*', :html, :json]
    

    After this, you can send a json object to sign_in.json or whatever you have set up in your routes for sign-in.

    {
      "user": {
        "email": "blah@blah.com",
        "password": "blah"
      }
    }
    

    And on success it will return 201 created, and the logged in user as a JSON object. On error it will return 401 with a JSON message indicating the reason for failure.

    Example:

    {"error":"Invalid email or password."}
    

    Here is a good example if you are using Backbone/Marionntte on the front end.

    http://joshhuckabee.com/integrating-devise-backbonejs

提交回复
热议问题