【问题标题】:Rails before_action with external authorization and callback带有外部授权和回调的 Rails before_action
【发布时间】:2021-01-07 05:14:03
【问题描述】:

对于我的用户控制器,我希望始终将用户作为@user 实例变量加载。这是通过使用回调从外部授权链接加载用户来完成的。

这是一个最小的例子:

class UsersController < ApplicationController

  before_action :authorize_user
  skip_before_action(:authorize_user, { :only => [:auth_callback] })


  # this is my before action meant to load in the @user instance variable
  def authorize_user

    # if user is not stored in session, get authorization from external link
    if !session.key?(:user_hash)
      redirect_to(external_auth_link)
    
    # otherwise, loads user from hash
    else
      user_hash = session[:user_hash]
      @user = get_user_from_hash(user_hash)
    end
  end

  
  # this is the callback from the external authorization link
  def auth_callback
    user = get_user_from_callback()
    session[:user_hash] = user.to_hash
    # the line in question
    # should I redirect here or what?
  end


  def page1
    # some page using the @user instance variable
    render({:template => "users/page1.html.erb"})
  end


  def page2
    # another page using the @user instance variable
    render({:template => "users/page2.html.erb"})
  end

end

在调用 page1 或 page2 时,我希望 before_action 正确加载到 @user 实例变量中,然后返回到相应的方法。

目前,当 user_hash 已经存储在 session 中时,before_action 可以正常工作。

但是,当 user_hash 没有保存在 session 中时,它会重定向外部授权,然后转到回调,然后不知道去哪里。它要我重定向或渲染某些东西。如何让它重定向到最初调用的操作(page1 或 page2)?

例如:如果我在 user_hash 未存储在会话中时调用 page1,它将转到:

  1. 授权用户
  2. 外部授权
  3. auth_callback
  4. 第1页

我已尝试删除与此问题无关的代码,但如果有其他任何帮助,请告诉我。感谢您的任何建议。

【问题讨论】:

  • 您是否可以控制此外部授权?它是否支持传入一些额外的参数,并在 auth 回调中返回?
  • 很遗憾没有。它的 Spotify 授权,它似乎不支持。

标签: ruby-on-rails


【解决方案1】:

如果可能,请尝试从处理身份验证并重定向到auth_callback 的服务中获取附加参数。该附加参数可以告诉您重定向到哪里。

如果不可能,那么您可以将当前操作保存到authorize_user 中的会话。

  def authorize_user

    # if user is not stored in session, get authorization from external link
    if !session.key?(:user_hash)
      # save action to session
      session[:redirect_to] = action_name

      redirect_to(external_auth_link)
    
    # otherwise, loads user from hash
    else
      user_hash = session[:user_hash]
      @user = get_user_from_hash(user_hash)
    end
  end

然后在回调中使用它来重定向。 请参阅 this topic 在 Rails 中获取操作名称。

或者,您也可以保存会话的完整路线或路径。

请记住,将其存储在会话中不是最佳选择,如果可以,请尝试从身份验证处理程序获取附加参数。

【讨论】:

  • 谢谢,我会在会话中存储。
  • 一个细微的变化:我使用request.fullpath 代替before_action,因为我需要路由的名称,而不是控制器操作来重定向。
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多