【问题标题】:Ruby 2.6.0 Invalid authenticity tokenRuby 2.6.0 无效的真实性令牌
【发布时间】:2019-06-20 09:11:55
【问题描述】:

我的代码显示“无效的真实性”而不是“缺少模板”。我需要在程序中进行哪些更改才能获得“缺少模板错误”? img1img2img3errorImg

对整个程序的引用如下: link to github resp

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

new.html.erb 下面:

新视图

<form action="/users" method="post" accept-charset="UTF-8">
  <label for="username">Username:</label><br>
  <input id="username" name="user[username]" type="text" /><br>
  <label for="email">Email:</label><br>
  <input id="email" name="user[email]" type="text" /><br>
  <label for="password">Password:</label><br>
  <input id="password" name="user[password]" type="text" /><br>
  <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>"> 
  <input type="submit" value="Submit">
</form>

route.rb

Rails.application.routes.draw do
  resources :users, only: [:new, :create]
end

【问题讨论】:

  • 请将代码添加到您的问题中(而不是图片)

标签: ruby-on-rails ruby ruby-2.6


【解决方案1】:

问题出在这一行:

 <input type="hidden" name="authenticity_token" value="form_authenticity_token %>">

这实际上应该是:

 <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">

否则,用于防止跨站点请求伪造攻击的真实性令牌将只是 'form_authenticity_token %>' 而不是真实令牌。

【讨论】:

  • 对不起。我的代码就是这样。我在发布时不小心重新格式化了错误的代码。我仍然得到错误。
【解决方案2】:

看起来您正在尝试使用 config/application.rb 进行protect_from_forgery

config.api_only = true

Here is your situation described

如果您将应用程序用作 API,您应该像这样重新生成它

$ rails new my_api --api

如果您需要更高的安全性,您可以将令牌存储在其他地方(不是 cookie 或会话) - 例如,您可以使用 JWT 令牌。 为了提高安全性,您还可以使用rack-cors gem 如果您不小心删除了资产并且不想使用 API,您可以将此配置设置为 false

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 2018-06-29
    • 2016-03-19
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多