【问题标题】:Specify resource routes that require authenticated user in Elixir Phoenix在 Elixir Phoenix 中指定需要经过身份验证的用户的资源路由
【发布时间】:2020-07-12 23:03:07
【问题描述】:

我在我的 Elixir Phoenix 应用程序中使用 phx_gen_auth 进行用户登录、注册和身份验证。它带有一个:require_authenticated_user 插件来决定特定路由是否需要用户在访问之前进行身份验证。

如果我的 router.ex 中有一个帖子资源,可以为我提供所有标准操作:

resources "/posts", PostController

如何才能最好地组织某些路线以要求用户登录?例如,查看所有帖子或查看单个帖子不需要登录。但是创建、编辑、更新、删除帖子需要用户登录。

有没有一种方法可以管理哪些路由需要身份验证,而无需在两个具有单独 pipe_throughs 的单独 scope 块中分别指定我的所有路由?

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    正如Phoenix.Router.pipeline/2 的文档中所述

    每次调用 pipe_through/1 时,新的管道都会附加到之前给出的管道上。

    也就是说,这会起作用:

    scope "/", MyWeb do
      pipe_through [:browser]
      get "/index", PostController
    
      pipe_through, :auth
      get "/show", PostController
      post "/create", PostController
      put "/update", PostController
    end
    

    另一种解决方案是直接在控制器中使用插件

    defmodule MyWeb.PostController do
      plug :auth when action in ~w|show create update|a
    
      def show(conn, params) do
        # ...
      end
    end
    

    【讨论】:

      【解决方案2】:

      我知道这样做的唯一方法是使用 2 个作用域。这是一个示例,其中我两次声明了相同的范围,但其中一个使用了额外的:auth 管道。请注意我如何使用:only 选项来指定允许哪些控制器方法:

        pipeline :browser do
          plug :accepts, ["html"]
          plug :fetch_session
          plug :fetch_flash
          plug :protect_from_forgery
          plug :put_secure_browser_headers
        end
      
        pipeline :auth do
          plug MyAppWeb.Auth
        end
      
        scope "/", MyAppWeb do
          pipe_through :browser
      
          resources "/posts", PostController, only: [:index]
        end
      
        scope "/", MyAppWeb do
          pipe_through :browser
          pipe_through :auth
      
          resources "/posts", PostController, only: [:show, :new, :create]
        end
      
      

      诀窍是使用:only 来说明允许以这种方式调用控制器中的哪些函数。路由器将匹配它找到的第一个,所以如果你在两个范围内使用相同的方法两次,比如:index,那么它将使用第一个范围(即第一个词法定义的范围。-第一个在文件)。

      我希望这是有道理的。如果你愿意,我可以解释更多。

      附:也许可以尝试一下,看看它是否有效:

        scope "/", MyAppWeb do
          pipe_through :browser
          resources "/posts", PostController, only: [:index]
      
          pipe_through :auth
          resources "/posts", PostController, only: [:show, :new, :create]
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 2020-09-04
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        相关资源
        最近更新 更多