Sean
Sean

Reputation: 3

Ruby 2.6.0 Invalid authenticity token

My code shows "Invalid Authenticity" instead of "missing template". What do I need to change in the program to get the "missing template error"? img1 img2 img3 errorImg

A reference to the entire program is here below: link to github resp

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

new.html.erb below:

New view

<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

Upvotes: 0

Views: 364

Answers (2)

smallbutton
smallbutton

Reputation: 3437

The problem is in this line:

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

This should actually be:

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

Since otherwise the authenticity token that is used to prevent cross site request forgery attacks will just be 'form_authenticity_token %>' instead of the real token.

Upvotes: 0

Yurii Verbytskyi
Yurii Verbytskyi

Reputation: 2052

Looks like you are trying to do protect_from_forgery with config/application.rb

config.api_only = true

Here is your situation described

If you will use your app as API, you should regenerate it like

$ rails new my_api --api

And if you need more security, you can store your tokens in other places(not cookie or session) - for example you can use JWT Tokens. For more security you can also use rack-cors gem And if you accidently removed assets and dont want to use API, you can set this config to false

Upvotes: 1

Related Questions