使用 Devise 时如何构建经过身份验证的路由? [英] How to structure authenticated routes when using Devise?

查看:24
本文介绍了使用 Devise 时如何构建经过身份验证的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的问题 如何当用户未登录 rails 时有 root 视图吗? max 回答说我们可以使用 authenticated 使路由仅在某人通过身份验证时可用.我有一个问题,我该如何构建这个:

In my question How to have root view when user is not logged in rails? max answered that we can use authenticated to make routes available only when someone is authenticated. I am having a probem that how can I structure this:

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 进行任何未经身份验证的操作,如何阻止?

The problem is I don't want to allow any unauthenticated action on :subjects how to stop that?

推荐答案

如果你想限制对主题的访问,你应该在控制器层进行——而不是在路由中.使用 before_action :authenticate_user! 将给出 401 Unauthorized 响应并重定向到登录.

If you want to limit access to subjects you should do it on the controller layer - not in the routes. Using before_action :authenticate_user! will give a 401 Unauthorized response and redirect to the sign in.

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

使用 authenticatedunauthenticated 路由助手非常有用,当您希望对经过身份验证和未经身份验证的用户的同一路由有不同的响应但不是您应该如何构建您的申请.

Using the authenticated and unauthenticated route helpers are useful when you want the have different responses for the same route for authenticated and unauthenticated users but is not how you should structure your application.

如果您只是在路由中使用 authenticated,未经身份验证的用户将收到 404 Not Found 响应,而不是被提示登录.这没有帮助.

If you simply use authenticated in your routes unauthenticated users will get a 404 Not Found response instead of being prompted to sign in. Which is not helpful.

还有 resources :students, only: [:get] 根本不生成任何路由.only 选项用于限制操作(显示、索引、编辑、更新...)而不是 HTTP 方法.使用 rake routes 查看应用中的路由.

Also resources :students, only: [:get] does not generate any routes at all. The onlyoption is for limiting the actions (show, index, edit, update ...) not the HTTP method. Use rake routes to see the routes in your app.

这篇关于使用 Devise 时如何构建经过身份验证的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆