从Rails获取authenticity_token

时间:2014-04-02 19:40:46

标签: ruby-on-rails ruby html5 authentication

我在Ruby中进行了一些身份验证(来自这个tutorial - 这个使用gem "bcrypt-ruby", :require => "bcrypt",我需要将authenticity_token写入json文件。我怎么能得到它并创建这个文件?

更新: 我写过:

  json.array!(@session) do |session|
      json.extract! session, :csrf-token
      json.url tag_url(session, format: :json)
    end

但它不起作用。我需要从html写

<meta content="authenticity_token" name="csrf-param" /> <meta content="74Mhbpn9FF/tY/cgfuVmX7ribN4rOkkdUjSgbLNsces=" name="csrf-token" />

此值:74Mhbpn9FF / tY / cgfuVmX7ribN4rOkkdUjSgbLNsces =

这是我的session_controller:

class SessionsController < ApplicationController
  def new
end

def index
  @session
end

def create
  user = User.authenticate(params[:email], params[:password])
  if user
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render "new"
  end
end

def destroy
  session[:user_id] = nil
  redirect_to root_url, :notice => "Logged out!"
end
end

1 个答案:

答案 0 :(得分:3)

有一个名为form_authenticity_token的视图助手可以像这样访问或分配令牌

def form_authenticity_token
  session[:_csrf_token] ||= SecureRandom.base64(32)
end

要使用session[:_csrf_token]

在控制器中抓取它