宝石" devise_token_auth"方法:authenticate_user!尽管有效的认证参数仍在返回401

时间:2016-03-15 07:10:46

标签: ruby ruby-on-rails-4 devise postman

我正在尝试使用gem" devise_token_auth"在每个json api请求上对用户进行身份验证。但是,我也希望支持传统的设计身份验证"config.enable_standard_devise_support = true"

#app/controllers/api/v1/api_controller.rb
class Api::V1::ApiController < ApplicationController
  respond_to :json
  include DeviseTokenAuth::Concerns::SetUserByToken
  before_filter :authenticate_user_from_token!
  ....
  def authenticate_user_from_token!
    user_email = request.headers["X-User-Email"].presence || request.headers["uid"].presence
    client_id = request.headers["client"].presence
    access_token = request.headers["access-token"].presence
    user = user_email && User.find_by_email(user_email)
    auth_token = request.headers["X-Auth-Token"].presence
    if user && auth_token && Devise.secure_compare(user.authentication_token, auth_token)
      sign_in user, store: false
      authenticate_user!
    elsif access_token && client_id && user && user.valid_token?(access_token, client_id)
      authenticate_user!
    else
      throw(:warden, scope: :user)
    end
  end
  ....
end

以下是相应的rspec

describe "Sign In" do
      it "allows further api requests with valid auth token and denies ones with invalid token" do
        post "/api/v1/sign_in", {"email": @user.email, "password": @user.password}, :format => :json
        expect_status(200)

        auth_header1 = response.header.slice('X-User-Email', 'X-Auth-Token', 'Content-Type')
        auth_header2 = response.header.slice('X-User-Email', 'X-Auth-Token', 'Content-Type')
        auth_header2["X-Auth-Token"] = "WRONGTOKEN"

        # Valid auth token
        get "/api/v1/cycle_days", {}, auth_header1
        expect_status(200)

        # Invalid auth token
        get "/api/v1/cycle_days", {}, auth_header2
        expect_status(401)

        # Cancan failure
        get "/api/v1/user/#{@user.id}", {}, auth_header2
        expect_status(301)
      end
    end

当用户成功登录后,当邮递员中的实际API失败时,这个rspec正在通过,所有这些API都返回401 {'error' : 'authentication error'}

0 个答案:

没有答案