简体   繁体   English

在 Rails 上的 Ruby 中带有 devise_token_auth 的“不允许的参数::用户,:会话”

[英]"Unpermitted parameters: :user, :session" with devise_token_auth in Ruby on Rails

I create an application using React and Ruby on Rails.我在 Rails 上使用 React 和 Ruby 创建了一个应用程序。

I want to register the application with devise_token_auth .我想用devise_token_auth注册应用程序。 But when I use devise in React, I see this in docker-compose:但是当我在 React 中使用 devise 时,我在 docker-compose 中看到了这个:

ruby_1      |   ↳ /usr/local/bundle/gems/activerecord-5.2.5/lib/active_record/log_subscriber.rb:98
ruby_1      | Processing by DeviseTokenAuth::RegistrationsController#create as HTML
ruby_1      |   Parameters: {"user"=>{"name"=>"KAITO", "email"=>"kaito24262426@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "registration"=>{"user"=>{"name"=>"KAITO", "email"=>"kaito24262426@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}
ruby_1      | Unpermitted parameters: :user, :registration
ruby_1      | Filter chain halted as :validate_sign_up_params rendered or redirected
ruby_1      | Completed 422 Unprocessable Entity in 1740ms (Views: 0.3ms | ActiveRecord: 0.0ms)
ruby_1      |

or或者


ruby_1      | Started POST "/api/v1/auth/sign_in" for 172.20.0.1 at 2021-05-16 16:10:58 +0900
ruby_1      | Processing by DeviseTokenAuth::SessionsController#create as HTML
ruby_1      | Parameters: {"user"=>{"email"=>"kaito24262426@gmail.com"}, "session"=>{"user"=>{"email"=>"kaito24262426@gmail.com"}}}
ruby_1      | Unpermitted parameters: :user, :session
ruby_1      | Completed 401 Unauthorized in 3ms (Views: 0.3ms | ActiveRecord: 0.0ms)

but when I use curl, I can success但是当我使用 curl 时,我可以成功

curl localhost:8000/api/v1/auth -X POST \
-d '{"email":"example@example.comm", "password":"password", "password_confirmation": "password", "name": "name"}' \
-H "content-type:application/json" 

{"status":"success", "data":{"id":9,"provider":"email","uid":"example@example.comm","allow_password_change":false,"name":null,"nickname":null,"image":null,"email":"example@example.comm","created_at":"2021-05-16T06:43:00.574Z","updated_at":"2021-05-16T06:43:00.836Z"}}

I can resolve to "Unpermitted parameters:" "name" or "email" or "password" and so on.我可以解析为“Unpermitted parameters:” “name” or “email” or “password” 等等。 but in this case, like "Unpermitted parameters: :user:register" case, I cant' look up something to resolve但在这种情况下,像“Unpermitted parameters::user:register”这样的情况,我无法查找要解决的问题

app/controller/application_controller.rb应用程序/控制器/application_controller.rb

class ApplicationController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken
  before_action :authenticate_user!, if: :devise_controller?, except: [:new, :create]
  skip_before_action :verify_authenticity_token, if: :devise_controller?, raise: false
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:user, :registration, :name, :email, :password, :password_confirmation])
  end
end

config/routes.rb配置/路由.rb

Rails.application.routes.draw do
  # devise_for :users
  namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
      resources :works
      resources :contents do
        resources :articles, only: %i[index]
      end
    end
  end
end

signUp.js (this is React file using axios) signUp.js (这是使用 axios 的 React 文件)

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import { Button, Form, FormGroup, Input, FormFeedback, Spinner } from 'reactstrap';
import { withRouter } from 'react-router-dom'
import { Formik } from 'formik';
import * as Yup from 'yup';
import "./Sign.css";

class SignUp extends Component {
  static propTypes = {
    show: PropTypes.bool, 
    setShow: PropTypes.func,
    anotherSetShow: PropTypes.func,
  };

  state = {
    loading: false,
  }

  _isMounted = false;

  handleOnSubmit = (values) => {
    if (this._isMounted) this.setState({ loading: true })
    axios.post("http://localhost:8000/api/v1/auth",
      {
        user: {
          name: values.name,
          email: values.email,
          password: values.password,
          password_confirmation: values.password_confirmation,
        }
      },
    )
    .then(res => {
      if (this._isMounted) this.setState({ loading: false });
      this.props.history.push("/works");
    })
    .catch(error => {
      console.log(error.response)
      if (this._isMounted) this.setState({ loading: false });
    });
  }

  componentDidMount = () => {
    this._isMounted = true;
  }

  componentWillUnmount = () => {
    this._isMounted = false;
  }

  openSignup = () => {
    this.props.setShow(false)
    this.props.anotherSetShow(true)
  }

  render() {
      return (
        <div className="container">
          <div className="text-right"><div className="batsu" onClick={() => this.props.setShow(false)}>✖︎</div></div>
          <h5><strong className="text-muted">アカウントを作成</strong></h5>
          <p><small className="text-muted">
            アカウントを作成することにより、利用規約 および プライバシポリシーに同意するものとします。<br />
            ユーザー名はランキングに表示されます。(設定で編集や非表示が可能です)
          </small></p>
          <div className="mx-auto" style={{ padding: 5, marginTop: 10 }}>
            <Formik
              initialValues={{ name: '', email: '', password: '', password_confirmation: '' }}
              onSubmit={(values) => this.handleOnSubmit(values)}
              validationSchema={Yup.object().shape({
                name: Yup.string(),
                email: Yup.string().email().required(),
                password: Yup.string().required(),
                password_confirmation: Yup.string().required(),
              })}
            >
              {
                ({ handleSubmit, handleChange, handleBlur, values, errors, touched }) => (
                  <Form onSubmit={handleSubmit}>
                    <FormGroup>
                      <Input
                        className="input"
                        type="text"
                        name="name"
                        id="name"
                        value={values.name}
                        placeholder="ユーザー名"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.name && errors.name ? true : false}
                      />
                      <FormFeedback>
                        {errors.name}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="email"
                        name="email"
                        id="email"
                        value={values.email}
                        placeholder="メールアドレス"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.email && errors.email ? true : false}
                      />
                      <FormFeedback>
                        {errors.email}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="password"
                        name="password"
                        id="password"
                        value={values.password}
                        placeholder="パスワード"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.password && errors.password ? true : false}
                      />
                      <FormFeedback>
                        {errors.password}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="password"
                        name="password_confirmation"
                        id="password_confirmation"
                        value={values.password_confirmation}
                        placeholder="パスワード(確認)"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.password_confirmation && errors.password_confirmation ? true : false}
                      />
                      <FormFeedback>
                        {errors.password_confirmation}
                      </FormFeedback>
                    </FormGroup>
                    <div style={{ textAlign: 'center' }}>
                      <Button className="mx-auto" color="info" type="submit" style={{ width: 400, minWidth: 270, padding: 10}} disabled={this.state.loading}>
                        <Spinner className="font-weight-bold mr-2" size="sm" color="light" hidden={!this.state.loading} />
                        新規登録
                      </Button>
                    </div>
                  </Form>
                )
              }
            </Formik>
          </div>
          <div className="text-muted">すでにアカウントをお持ちですか?<div style={{ color: "#0000ff", cursor: 'pointer'}} onClick={() => this.openSignup(true)}>ログイン</div></div>
        </div>
      );
  }
}

export default withRouter(SignUp);

Seems like issue is here.似乎问题就在这里。

 def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:user, :registration, :name, :email, :password, :password_confirmation])
  end

Change it to将其更改为

 def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :email, :password, :password_confirmation])
  end

and handleOnSubmit ashandleOnSubmit

 handleOnSubmit = (values) => {
    if (this._isMounted) this.setState({ loading: true })
    axios.post("http://localhost:8000/api/v1/auth",
      {
          name: values.name,
          email: values.email,
          password: values.password,
          password_confirmation: values.password_confirmation,
        
      },
    )
    .then(res => {
      if (this._isMounted) this.setState({ loading: false });
      this.props.history.push("/works");
    })
    .catch(error => {
      console.log(error.response)
      if (this._isMounted) this.setState({ loading: false });
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM