【问题标题】:Why is Rails authentication controller route duplicating auth params?为什么 Rails 身份验证控制器路由重复身份验证参数?
【发布时间】:2019-12-24 01:56:04
【问题描述】:

我在 rails 控制器中有 signupsignin POST 路由。 signup 需要 emailpasswordpassword_confirmationsignin 需要 emailpassword

以下是路线的样子:

class Api::V1::AuthController < ApplicationController

  def signup
    binding.pry <-- inspect the params here
    @user = User.create(user_credential_params)
    if @user.valid?
      @token = encode_token(:user_id => @user.id)
      render json: { :user => @user, :jwt => @token }, :status => :created
    else
      render json: { :error => 'Failed to create user' }, :status => :not_acceptable
    end
  end

  def signin
    @user = User.find_by(:email => user_credential_params[:email])
    # authenticate method comes from bcrypt
    if @user && @user.authenticate(user_credential_params[:password])
      @token = encode_token({ :user_id => @user.id })
      render json: { :user => @user, :jwt => @token }, :status => :accepted
    else
      render json: { :error => 'Invalid credentials' }, :status => :unauthorized
    end
  end

  private

  def user_credential_params
    params.permit(:email, :password, :password_confirmation)
  end
end

还有routes.rb:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      post '/signup', to: 'auth#signup'
      post '/signin', to: 'auth#signin'
    end
  end
end

如果我在任一控制器操作中抛出 binding.pry 来检查参数(在本例中我正在检查 signup),我会看到以下参数(通过 Postman 并在浏览器中使用 AXIOS):

[1] pry(#&lt;Api::V1::AuthController&gt;)&gt; params

=&gt; &lt;ActionController::Parameters {"email"=&gt;"joelhoelting@aol.com", "password"=&gt;"password123", "password_confirmation"=&gt;"password123", "controller"=&gt;"api/v1/auth", "action"=&gt;"signup", "auth"=&gt;{"email"=&gt;"joelhoelting@aol.com", "password"=&gt;"password123", "password_confirmation"=&gt;"password123"}} permitted: false&gt;

您可以看到上述参数在另一个 [:auth] 参数哈希中返回了 emailpasswordpassword_confirmation 的重复项。但是,我没有在邮递员或浏览器中提供名为 [:auth] 的参数。

[:auth] 参数来自哪里? rails 会自动添加该参数吗?如果是,为什么?

如果上下文仍然不清楚,这里是 Github Repo: Link To Repo

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    是的,当发送到服务器的 JSON 未指定任何根元素时,Ruby on Rails 会自动使用当前控制器名称 wraps parameters

    您可以在config/initializers/wrap_parameters.rb 中重新配置此行为。

    【讨论】:

      【解决方案2】:

      rails 是否会自动添加该参数,如果是,为什么?

      是的

      当我在 signin 动作中抛出 binding.pry 时。然后输入Thread.current.backtrace

      我看到action_controller/metal/params_wrapper.rb 中的process_action 方法被调用。这是source code

      据此,当wrap parameters format 包含请求的内容类型时,Ruby on Rails 会自动将参数包装为当前控制器名称。就像@spickermann 说的那样。

      【讨论】:

        猜你喜欢
        • 2012-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        • 2021-12-20
        • 2016-12-11
        • 1970-01-01
        • 2016-04-12
        相关资源
        最近更新 更多