简体   繁体   English

Ruby on Rails-RESTful API身份验证

[英]Ruby on Rails - RESTful API Authentication

Im building a simple REST API with ruby on rails that allows users to easily create an account. 我用红宝石构建了一个简单的REST API,使用户可以轻松创建一个帐户。 Recently I have tried to secure the API with an API token. 最近,我尝试使用API​​令牌保护API。 I have been testing my API with the Advanced Rest Client that is found on the Google chrome web store. 我一直在使用Google Chrome网上商店中的Advanced Rest Client测试我的API。 As far as I know it has worked as when I try to access the calls I get a message from my REST client test application that looks like this: 据我所知,当我尝试访问这些呼叫时,它会从REST客户端测试应用程序中收到一条消息,如下所示:

在此处输入图片说明

The problem comes when I try to authenticate successfully with the Advanced Rest Client . 当我尝试使用Advanced Rest Client成功进行身份验证时,就会出现问题。 Here is the controller code that I use to create the token and check to see if the user authenticated: 这是我用来创建令牌并检查用户是否通过身份验证的控制器代码:

class Api::UserController < ApplicationController
  skip_before_filter  :verify_authenticity_token

  TOKEN = "secret"
  before_action :authenticate

  def index
    @users = User.all

    respond_to do |format|
      format.json { render json: @users }
    end
  end

  def create
    @user = User.new()
    @user.first_name = params[:first_name]
    @user.last_name = params[:last_name]
    @user.email = params[:email]
    @user.password = params[:password]

    respond_to do |format|
      if @user.save
        @response = {:status => "201", :message => "User successfully created."}
        format.json { render json: @response, status: :created }
      else
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end


  # private methods in the UserController class
  private

  def authenticate
    authenticate_or_request_with_http_token do |token, options|
      token == TOKEN
    end
  end
end

It's fairly simple and seems to be doing its job as I haven't been able to authenticate with the Advanced Rest Client . 它非常简单,并且似乎正在执行其工作,因为我无法通过Advanced Rest Client进行身份验证。 I have tried to set an API token in the HTTP headers but can't seem to get the syntax correct. 我试图在HTTP标头中设置API令牌,但似乎无法正确获取语法。 Here are a few examples of what I have tried: 以下是我尝试过的一些示例:

在此处输入图片说明

and, 和,

在此处输入图片说明

and finally, 最后,

在此处输入图片说明

What am I doing wrong? 我究竟做错了什么? Is the API token not stored in a HTTP header? API令牌是否未存储在HTTP标头中? Please help! 请帮忙!

Your header is incorrect, the key should be Authorization 您的标题不正确,密钥应为Authorization

Try putting this as the Raw header: 尝试将其作为Raw标头:

Authorization: Token token=secret

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM