【问题标题】:devise: how to allow unauthenticated access to some pages?设计:如何允许未经身份验证的访问某些页面?
【发布时间】:2017-08-04 16:14:03
【问题描述】:

我已经实现了带有设计身份验证的 Rails。作为该过程的一部分,我在 application_controller 中添加了一个“全局”before_action :authenticate_user!,它要求所有页面都必须经过身份验证。

# app/controllers/application_controllers.rb

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

如何在不要求用户先登录的情况下允许访问某些控制器#actions。

这在发送大量电子邮件时很有用,并且电子邮件包含指向通常需要身份验证的 #show 操作的链接。

【问题讨论】:

    标签: ruby-on-rails devise


    【解决方案1】:

    skip_before_action :authenticate_user! 放入控制器中以允许该控制器的所有操作。

    您还可以结合使用onlyexcept 关键字来仅允许或禁止特定操作。

    # skips authentication only for "index" and "show"
    skip_before_action :authenticate_user! only: %i[index show]
    
    # requires authentication only for "update" and "destroy"
    skip_before_action :authenticate_user! except: %i[update destroy]
    

    【讨论】:

      【解决方案2】:

      在控制器中只需提及需要登录的操作:

       before_action :authenticate_user!, :only => [:new, :create, :edit]
      

      例如,如果您在控制器中有操作“send_mail”,则无需登录即可访问。

      【讨论】:

      • 我有一个全局的 before_action :authenticate_user!在 application_controller 中
      • 这种情况下,如果没有登录,您将无法访问任何控制器中的任何操作
      猜你喜欢
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多