简体   繁体   English

跳过JSON POST API的用户和csrf身份验证

[英]Skip user and csrf authentication for JSON POST APIs

Is there a way to skip require_user for JSON APIs. 有没有一种方法可以跳过require_user以获取JSON API。

I have a web application that sends JSON POST requests to my rails app and expects a JSON response. 我有一个Web应用程序,该应用程序将JSON POST请求发送到我的rails应用程序,并且期望JSON响应。 However, each request is being redirected to the login page as (I assume) it is not being registered as having a session. 但是,每个请求都被重定向到登录页面,因为(我假设)它没有被注册为具有会话。

So far this is what I have: 到目前为止,这就是我所拥有的:

memo_main_tester_controller.rb memo_main_tester_controller.rb

class MemoMainTesterController < ApplicationController

  before_action :require_user, unless: :json_request?
  ...

This is where API methods are 这是API方法所在的地方

application_controller.rb application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery
  skip_before_action :verify_authenticity_token, if: :json_request?

  helper_method :current_user
  ...

  def json_request?
    request.format.symbol == :json
  end

  private
  def current_user
    User.where(id: session[:user_id]).first
  end

  def require_user
    the_user = current_user
    unless the_user
      redirect_to login_path, notice: 'You must be logged in to view that page.'
    end
  end

I got the method json_request? 我有方法json_request? from a search through SO, but I don't think it's working. 通过SO搜索,但我认为它没有用。

When I send a POST request to the memo_main_tester_controller the AJAX request hits a 302 and I am sent the login page with a 200 . 当我向memo_main_tester_controller发送POST请求时,AJAX请求命中302并向我发送登录页面200 How do I stop this and get my expected JSON response? 如何停止此操作并获得预期的JSON响应?

You app should be working on this stage. 您的应用程序应在此阶段工作。 json_request? looks fine too. 看起来也不错。 Thought there is a more generic way to rewrite it : 以为有一种更通用的重写方法:

def json_request?
  request.format.json?
end

I think issue should be your request URL you call from your AJAX call is not ending with .json . 我认为问题应该是您从AJAX调用中调用的请求URL不以.json结尾。

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

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