过滤链停止为:authenticate_with_token!渲染或重定向的导轨API



因此,我正在处理带有位置的基于位置的API,其中一个位置有很多用户,并且在特定时间的位置属于一个位置。这意味着用户表将包含一个用作外键的位置_id列。但是,这与我访问过的大多数应用程序不同,例如,用户将拥有许多"产品"。因此,我在我的位置_controller.rb文件

class Api::V1::LocationsController < ApplicationController
    before_action :authenticate_with_token!, only: [:create]
    respond_to :json
    def show
        respond_with Location.find(params[:id])
    end
    def create
        # @location = current_user.locations.build(location_params)
        @location = Location.new(location_params)
        current_user.location = @location
        current_user.save
        if @location.save
            render json: @location, status: :created, location: [:api, :v1, @location]
        else
            render json: {errors: @location.errors}, status: :unprocessable_entity
        end
    end
    private

    def location_params
        params.require(:location).permit(:latitude, :longitude, :address)
    end
end

,但我得到了错误

Started POST "/api/v1/locations" for 127.0.0.1 at 2016-12-20 10:05:50 +0100
Processing by Api::V1::LocationsController#create as JSON
  Parameters: {"location"=>{"latitude"=>"2.23413", "longitude"=>"2.908019", "address"=>"Sims1 streets"}}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."auth_token" IS NULL LIMIT 1
Filter chain halted as :authenticate_with_token! rendered or redirected
Completed 401 Unauthorized in 5ms (Views: 0.2ms | ActiveRecord: 0.5ms)

我的问题是:如何解决?我到处搜索,但无济于事。请帮助

我的authenticable.rb文件是

module Authenticable
  # Devise methods overrides. This finds the user by auth_token and it's sent to the server
  def current_user
    @current_user ||= User.find_by(auth_token: request.headers["Authorization"])
  end
  def authenticate_with_token!
    render json: { errors: "Not authenticated" }, status: :unauthorized unless user_signed_in?
  end
  def user_signed_in?
    current_user.present?
  end
end

您正在调用一个回调困扰创建动作

before_action :authenticate_with_token!, only: [:create]

因此,每当您去此操作时,都会要求有效的身份验证令牌,直到提供有效的身份验证令牌才能执行该操作。

您可以在控制台中看到

 User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."auth_token" IS NULL LIMIT 1

用户身份令牌为null。

请尝试在Craete Action之前向身份验证用户发送有效的验证。

您的用户表中可能有一个auth_token列。尝试为任何用户找到Authentication_Token,并将其传递到您的URL

 /api/v1/locations?user_token= your token 

最新更新