提交表单时出现此错误。表单确实有一个隐藏的_csrf_token字段,如以下屏幕截图所示:
但是,提交令牌后,令牌将无法通过验证:
[debug] ** (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Request
Forgery) token, make sure all requests include a valid '_csrf_token' param or
'x-csrf-token' header
(plug) lib/plug/csrf_protection.ex:233: Plug.CSRFProtection.call/2
我的代码很标准:
router.ex
scope "/account" do
pipe_through :browser
get "/redeem/:token", MyAppWeb.Accounts.AccountController, :verify_invitation
post "/redeem", MyAppWeb.Accounts.AccountController, :redeem_invitation
end
account_controller.ex
#renders the form
def verify_invitation(conn, %{"token" => token}) do
conn
|> put_status(:ok)
|> put_flash(:info, "Invitation verified. Please choose a password.")
|> put_view(MyAppWeb.Accounts.AccountView)
|> render("redeem.html", invitation: invitation)
end
#simplified
def redeem_invitation(conn, %{"token" => token, "user" => %{"password" => password, "password_confirmation" => password_confirmation}}) do
conn
|> redirect(external: MyAppWeb.Router.Helpers.login_page_url(conn, MyAppWeb.Endpoint, :new) <> "?action=redeem")
end
redeem.html.eex
<%= form_for @conn, redeem_invitation_path(@conn, :redeem_invitation), fn f -> %>
# stuff
<%= submit "Create Account", class: "btn btn-indigo ml-0" %>
<% end %>
为什么CSRF令牌无法通过验证?