gpt4 book ai didi

javascript - 处理 rails 中 navigator.sendBeacon 请求的 CSRF 真实性 token

转载 作者:行者123 更新时间:2023-12-02 15:00:47 27 4
gpt4 key购买 nike

    $(window).on('unload', function() {
db.flipCounter.get(gon.slug, function(obj) {
var payload = {
slug: gon.slug,
localFlipCount: obj.fc,
time: Date.now()
}

navigator.sendBeacon('/analytics', csrfProtect(payload))

})
})

function csrfProtect(payload) {
var param = $("meta[name=csrf-param]").attr("content")
var token = $("meta[name=csrf-token]").attr("content")

if (param && token) payload[param] = token
return new Blob([JSON.stringify(payload)], { type: "application/x-www-form-urlencoded; charset=utf-8" })
}

在上面的代码中,我希望使用有效负载将 POST 发送到“/analytics”url。我收到以下错误(警告)... 试图触发请求:

Promise.js:840 Unhandled rejection: TypeError: Cannot create property 'authenticity_token' on string '{"slug":"test-page-by-marvin-danig","localFlipCount":1,"time":1524241435403}'

嗯。

...发出请求,我得到:

Processing by BooksController#analytics as */*
Parameters: {"{\"slug\":\"test-book-by-marvin-danig\",\"localFlipCount\":1,\"time\":1524243279653,\"param\":\"8rzDx/TNL8YeU1/NWgWSk6gB/UvmbB9Ip VajDCgfDUv5Q4pjh7x0GUG1il1jDJajtJyHf84Xv5Pt14fiCnA9w"=>"=\"}"}
Can't verify CSRF token authenticity.
exception
ActionController::InvalidAuthenticityToken

更新:问题仍未解决。这是我现在所在的位置:

我在 routes.rb 上打开了以下 GET 和 POST 路由:

# Analytics (flipCounter)
get 'auth_token', to: 'analytics#auth_token'
post 'receptor', to: 'analytics#receptor', as: :receptor

这些显然像这样映射到 analytics_controller:

class AnalyticsController < ApplicationController
respond_to :js

def auth_token
session[:_csrf_token] = form_authenticity_token
end

def receptor
logger.debug "Check book slug first: #{params}"

begin
book = Book.friendly.find(params[:slug])
rescue ActiveRecord::RecordNotFound => e
book = nil
end

if book.exists?
book.flipcount += params[:flipcount].to_i
end

end
private

end

除了 auth_token 方法外,我还得到了一个 auth_token.json.erb 模板,该模板按以下方式提供:

{ "authenticity_token": "<%= session[:_csrf_token] %>" } 

而客户端 javascript(糟糕的草稿)采用以下方式:

            // When state of book changes to `not_flipping`:

flipCount += 1

const o = { slug: gon.slug, fc: flipCount }

// IndexedDb initiated elsewhere.
db.transaction('rw', db.flipCounter, function(e) {
db.flipCounter.put(o)
}).then(function(e) {
const URL = '/auth_token' // First fetch the authenticity_token!
fetch(URL, {
method: 'GET'
}).then(function(res) {
return res.json()
}).then(function(token) {


return postBookData(token)


}).catch(err => console.log(err))
}).catch(function(e) {
console.log(e)
})


function postBookData(token) {

db.flipCounter.get(gon.slug, function(obj) {
// var payload = new FormData()

// payload.append('slug', gon.slug)
// payload.append('localFlipCount', obj.fc)
// payload.append('authenticity_token', token.authenticity_token)
// payload.append('type', 'application/x-www-form-urlencoded;')
// payload.append('charset=utf-8', 'ok')
// payload.append('X-CSRF-Token', token.authenticity_token)

//var payload = { 'slug': gon.slug }

let body = {
slug: gon.slug,
flipcount: obj.fc,
time: Date.now()
}
let headers = {
type: 'application/x-www-form-urlencoded; charset=utf-8',
'X-CSRF-Token': token.authenticity_token
}
let blob = new Blob([JSON.stringify(body)], headers);
let url = '/receptor'

navigator.sendBeacon(url, blob);

}).then(function() {
flipCount = 0
var o = { slug: gon.slug, fc: flipCount }
}).catch(err => console.log(err))
}

navigator.sendBeacon 触发的请求对象不正确,因为 X-CSRF-Token 未设置,我显然在服务器端:

Started POST "/receptor" for 127.0.0.1 at 2018-04-26 09:00:33 -0400
Processing by AnalyticsController#receptor as */*
Parameters: {"{\"slug\":\"bookiza-documentation-by-marvin-danig\",\"fc\":1}"=>nil}
Can't verify CSRF token authenticity.
exception
ActionController::InvalidAuthenticityToken
Rendering public/500.html
Rendered public/500.html (1.0ms)
Completed 500 Internal Server Error in 337ms (Views: 335.8ms | ActiveRecord: 0.0ms)

有没有人在 Rails 应用程序上使用服务 worker 在完全离线的页面上实现了 navigator.sendBeacon 场景?

最佳答案

刚刚遇到这个问题,我的解决方案的js端如下:

window.addEventListener("unload", function() {
var url = "/your_metrics_path",
data = new FormData(),
token = $('meta[name="csrf-token"]').attr('content');
// add your data
data.append("foo", "bar");
// add the auth token
data.append("authenticity_token", token);
// off she goes
navigator.sendBeacon(url, data);
});

希望这对您有所帮助。

关于javascript - 处理 rails 中 navigator.sendBeacon 请求的 CSRF 真实性 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49946055/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com