常见设计登录web和api [英] Common Devise login for web and api

查看:145
本文介绍了常见设计登录web和api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个rails应用程序,它有一个网站和api(这将由我的Android应用程序)。

I am working on a rails application which has a both a website and an api(which will be consumed by my android app).

我已经在controllers / api目录下创建了单独的控制器来处理所有的api控制器代码,控制器处理网站直接在controllers文件夹下

I have created separate controllers under controllers/api directory to handle all the api controllers code, the controllers to handle website are directly under controllers folder

我使用Devise在我的网站认证,现在我想扩展设计认证系统,以便它可以同时支持api和Web认证,即一个人可以登录/注册使用来自web和api的相同凭据。

I am using Devise for authentication in my website and now I want to extend the devise authentication system so that it can support both api and web authentication at the same time i.e a person can login/signup using the same credentials from web and from api.

我使用 simple_token_authentication gem启用令牌身份验证。

I am using simple_token_authentication gem to enable token authentication with devise.

我正在关注此博文,以便为devise实现基于令牌的身份验证 - :
http://provoost.tumblr.com/post/80873086965/json-api-authentication-using-devise-tokens

I am following this blog post to implement token based authentication for devise -: http://provoost.tumblr.com/post/80873086965/json-api-authentication-using-devise-tokens

我的路径文件的代码是

 Rails.application.routes.draw do
  resources :products
  devise_for :users
  root 'products#index'

  namespace :api do
   devise_for :users, :controllers => {registrations: "api/registrations", sessions: "api/sessions"}
  end

end

我在devise.rb文件中添加了这一行:

I added this line in my devise.rb file:

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



我在控制器下创建了会话控制器和注册控制器/ api目录

I created sessions controller and registrations controller under controller/api directory

会话控制器代码

   class API::SessionsController < Devise::SessionsController

   def create
    self.resource = warden.authenticate!(auth_options)
    sign_in(resource_name, resource)

    current_user.update authentication_token: nil

    respond_to do |format|
     format.json {
     render :json => {
       :user => current_user,
       :status => :ok,
       :authentication_token => current_user.authentication_token
      }
     }
   end
   end

   # DELETE /resource/sign_out
   def destroy

     respond_to do |format|
     format.json {
       if current_user
        current_user.update authentication_token: nil
        signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
        render :json => {}.to_json, :status => :ok
       else
        render :json => {}.to_json, :status => :unprocessable_entity
       end


       }
     end
    end
   end 

注册控制器的代码:

        class API::RegistrationsController < Devise::RegistrationsController

          def create
            @user = User.create(user_params)
            if @user.save
              render :json => {:state => {:code => 0}, :data => @user }
            else
              render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
            end

          end

          private

          def user_params
            params.require(:user).permit(:email, :password)
          end
        end            class API::RegistrationsController < Devise::RegistrationsController

          def create
            @user = User.create(user_params)
            if @user.save
              render :json => {:state => {:code => 0}, :data => @user }
            else
              render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
            end

          end

          private

          def user_params
            params.require(:user).permit(:email, :password)
          end
        end 

此外,为了测试目的我禁用了csrf标签

Also, for test purpose I disabled the csrf tags

现在,我试图从curl发送以下请求

Now, I am trying to send the following requests from curl

1)Sign_up

1) Sign_up

 curl -H 'Content-Type: application/json'   -H 'Accept: application/json' -X POST http://localhost:3000/api/users.json   -d '{"user": {"email": "test@test.com", "password": "12345678"}}'

此请求正常工作,正在创建新用户

This request is working fine and is creating the new user

2)Sign_in

2) Sign_in

curl -H 'Content-Type: application/json'   -H 'Accept: application/json' -X POST http://localhost:3000/api/users/sign_in   -d '{"user": {"email": "a@a.com", "password": "12345678"}}'

当我尝试使用此请求进行sign_up时,会抛出以下错误:

When I am trying to sign_up using this request, it is throwing the following error:

    Started POST "/api/users/sign_in" for 127.0.0.1 at 2015-08-17 17:48:52 +0530
    Processing by API::SessionsController#create as JSON
      Parameters: {"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}}}
    Completed 401 Unauthorized in 2ms (ActiveRecord: 0.0ms)
    Processing by API::SessionsController#new as JSON
      Parameters: {"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}}}
    Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)

    NoMethodError (undefined method `users_url' for #<API::SessionsController:0x007ff4ca92ad80>):
      actionpack (4.2.3) lib/action_dispatch/routing/polymorphic_routes.rb:220:in `polymorphic_method'
      actionpack (4.2.3) lib/action_dispatch/routing/polymorphic_routes.rb:114:in `polymorphic_url'
      actionpack (4.2.3) lib/action_dispatch/routing/url_for.rb:163:in `url_for'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:95:in `_process_options'
      actionpack (4.2.3) lib/action_controller/metal/streaming.rb:200:in `_process_options'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:43:in `block in _render_to_body_with_renderer'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/set.rb:283:in `each_key'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/set.rb:283:in `each'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:41:in `_render_to_body_with_renderer'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:37:in `render_to_body'
      actionpack (4.2.3) lib/abstract_controller/rendering.rb:25:in `render'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:16:in `render'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
      activesupport (4.2.3) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
      activesupport (4.2.3) lib/active_support/core_ext/benchmark.rb:12:in `ms'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
      activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:43:in `render'
      responders (2.1.0) lib/action_controller/responder.rb:258:in `display'
      responders (2.1.0) lib/action_controller/responder.rb:214:in `api_behavior'
      responders (2.1.0) lib/action_controller/responder.rb:191:in `rescue in to_format'
      responders (2.1.0) lib/action_controller/responder.rb:185:in `to_format'
      responders (2.1.0) lib/action_controller/responder.rb:163:in `respond'
      responders (2.1.0) lib/action_controller/responder.rb:156:in `call'
      responders (2.1.0) lib/action_controller/respond_with.rb:203:in `respond_with'
      devise (3.5.2) app/controllers/devise/sessions_controller.rb:12:in `new'
      actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:10:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
      activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:553:in `block (2 levels) in compile'
      activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:88:in `run_callbacks'
      actionpack (4.2.3) lib/abstract_controller/callbacks.rb:19:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/rescue.rb:29:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
      activesupport (4.2.3) lib/active_support/notifications.rb:164:in `block in instrument'
      activesupport (4.2.3) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
      activesupport (4.2.3) lib/active_support/notifications.rb:164:in `instrument'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
      activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process'
      actionview (4.2.3) lib/action_view/rendering.rb:30:in `process'
      actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action'
      devise (3.5.2) lib/devise/failure_app.rb:53:in `call'
      devise (3.5.2) lib/devise/failure_app.rb:53:in `recall'
      devise (3.5.2) lib/devise/failure_app.rb:37:in `respond'
      actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process'
      actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action'
      devise (3.5.2) lib/devise/failure_app.rb:22:in `call'
      devise (3.5.2) lib/devise/failure_app.rb:22:in `call'
      devise (3.5.2) lib/devise/delegator.rb:5:in `call'
      warden (1.2.3) lib/warden/manager.rb:130:in `call_failure_app'
      warden (1.2.3) lib/warden/manager.rb:116:in `process_unauthenticated'
      warden (1.2.3) lib/warden/manager.rb:47:in `call'
      rack (1.6.4) lib/rack/etag.rb:24:in `call'
      rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
      rack (1.6.4) lib/rack/head.rb:13:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call'
      rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
      rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call'
      activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call'
      activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
      activerecord (4.2.3) lib/active_record/migration.rb:377:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks'
      actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
      web-console (2.2.1) lib/web_console/middleware.rb:39:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
      railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app'
      railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged'
      railties (4.2.3) lib/rails/rack/logger.rb:20:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
      rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
      rack (1.6.4) lib/rack/runtime.rb:18:in `call'
      activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
      rack (1.6.4) lib/rack/lock.rb:17:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call'
      rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
      railties (4.2.3) lib/rails/engine.rb:518:in `call'
      railties (4.2.3) lib/rails/application.rb:165:in `call'
      rack (1.6.4) lib/rack/lock.rb:17:in `call'
      rack (1.6.4) lib/rack/content_length.rb:15:in `call'
      rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'


      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.1ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.5ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.4ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (34.6ms)
    Cannot render console with content type application/jsonAllowed content types: [#<Mime::Type:0x007ff4d7750b10 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x007ff4d77507f0 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x007ff4d7748488 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

完整代码也可以在 https://github.com/lovishchoudhary/devisetest

任何人都可以帮我找出我在做什么错误?

Can anybody please help me figure out what error I am doing ?

推荐答案

@Lovish Choudhary我发现您使用

@Lovish Choudhary I found you sent request for sign up with

http://localhost:3000/api/users/sign_in URL.

但是你定义了你的注册路由 api / registrations

But you defined that your registration route with api/registrations

由于您的路由文件中有多个设备路由,因此发生问题。

Problem occurred as you have multiple devise routeing in your route file.

这篇关于常见设计登录web和api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆