Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

ruby on rails - Using Devise 1.3 to authenticate JSON login requests

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 adds support for JSON as well but I cant find any examples or literature on it.

Can someone please point me to any resource for this or provide some sample code?

Thanks! Satyam

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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": "[email protected]",
    "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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...