【问题标题】:How to structure authenticated routes when using Devise?使用 Devise 时如何构建经过身份验证的路由?
【发布时间】:2017-04-16 04:30:30
【问题描述】:
在我的问题How to have root view when user is not logged in rails? max 中回答说,我们可以使用authenticated 使路由仅在某人通过身份验证时可用。我有一个问题,我该如何构建这个:
Rails.application.routes.draw do
devise_for :users
authenticated :user do
# when authenticated allow all action on student
resources :subjects do
resources :students
end
end
# when not only allow read on student
resources :subjects do
resources :students, only: [:get]
end
root "home#index"
end
问题是我不想允许对:subjects 进行任何未经身份验证的操作,如何阻止?
【问题讨论】:
标签:
ruby-on-rails
devise
warden
【解决方案1】:
如果您想限制对主题的访问,您应该在控制器层上进行 - 而不是在路由中。使用before_action :authenticate_user! 将给出401 Unauthorized 响应并重定向到登录。
class ApplicationController
# secure by default
before_action :authenticate_user!, unless: :devise_controller?
end
class SubjectsController < ApplicationController
# whitelist actions that should not require authentication
skip_before_action :authenticate_user!, only: [:show, :index]
# ...
end
Rails.application.routes.draw do
devise_for :users
resources :subjects do
resources :students
end
root "home#index"
end
当您希望经过身份验证和未经身份验证的用户对同一路由有不同的响应时,使用 authenticated 和 unauthenticated 路由助手很有用,但不是您应该构建应用程序的方式。
如果您只是在路由中使用 authenticated,则未经身份验证的用户将收到 404 Not Found 响应,而不是提示登录。这没有帮助。
另外resources :students, only: [:get] 根本不生成任何路由。 onlyoption 用于限制操作(显示、索引、编辑、更新...)而不是 HTTP 方法。使用rake routes 在您的应用中查看路线。
【解决方案2】:
这是构建已验证和未验证路由的简单方法。
在 app/controllers/application_controller.rb 中,添加
"before_action :authenticate_user!"。
我的 app/controllers/application_controller.rb 文件:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
end
我的配置/routes.rb:
Rails.application.routes.draw do
devise_for :users
root "home#index"
devise_for :users, controllers: {
:sessions => "users/sessions",
:registrations => "users/registrations" }
authenticated :user do
resources :students
end
unauthenticated :user do
#Some route
end
end