【问题标题】:Ruby on rails web app and api side by side issueRuby on rails web 应用程序和 api 并排问题
【发布时间】:2019-05-04 00:57:05
【问题描述】:

我是 Ruby on rails 的新手。我需要维护一个完整的网络应用程序。现在我需要在其中引入 API。我已经分别搜索并获得了许多关于 API 和 Web 应用程序的教程。但是没有得到任何人展示这些东西将如何协同工作。我很困惑该身份验证如何对两者起作用。 这是application_controller.rb:

class ApplicationController < ActionController::Base
  helper_method :sort_column, :sort_direction

  protect_from_forgery

  before_filter :authenticate_user!
  # before_filter :authenticate # HTTP AUTH DISABLED

  rescue_from CanCan::AccessDenied do |exception|
    render :file => "#{Rails.root}/public/403.html", :status => 403, :layout => false
    ## to avoid deprecation warnings with Rails 3.2.x (and incidentally using Ruby 1.9.3 hash syntax)
    ## this render call should be:
    # render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: false
  end  

  def user_for_paper_trail
    if user_signed_in?
      current_user.full_name
    end
  end

  def info_for_paper_trail
    if user_signed_in?      
      { :user_id => current_user.id }
    end
  end    

  protected
  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == "123"
    end
  end  

end

我需要知道如何验证 API?如果我使用 JWT,那么如何覆盖 sign_in 方法并为 API 单独执行所有这些操作,这对我来说也是开销,因为身份验证已经存在。 此外,如果我知道如何在控制器中涉及 API 函数会有所帮助吗?就像我有用户控制器和网络应用程序的所有方法一样。现在我需要相同的 API 方法。所以我需要为 API 制作新的控制器或者可以使用那个控制器?

【问题讨论】:

    标签: ruby-on-rails ruby authentication jwt


    【解决方案1】:

    这里有很多问题,所以我会尝试给出一个宏观的答案:

    一般来说,其他控制器继承自 ApplicationController(在您的情况下)运行 before_filter。过滤器可以重定向或渲染,从而阻止特定路由的执行。由于所有控制器都继承自 ApplicationController,因此过滤器会在应用的每个操作之前运行(假设最常见的默认情况)。

    据推测,API 身份验证的工作方式应该不同于应用程序的 html 前端(可能是标头中的 api 密钥)。您的应用似乎正在使用 https://github.com/plataformatec/devise。我会看看它,看看你是否可以用它为你的 API “打开”一个合适的身份验证方法。

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      对我有用的解决方案是将友好的令牌与 devise_token_auth 一起用于 api。这是我之前的过滤器:

      before_filter do
      if check_api_request
        authenticate_api_request
      else
        authenticate_user!
      end
      

      结束

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-05
        相关资源
        最近更新 更多