所以,对于我的生活,我无法弄清楚如何不将大猩猩的csrf直接注入田地。它一直在谈论通过标题和cookie传递它,但我做的任何事情似乎都没有...这就是我的go服务器所拥有的:
`
package main
import (
"gorilla/mux"
"gorilla/csrf"
"net/http"
"log"
"encoding/json"
"http/template"
"time"
)
func showLoginPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Set-Cookie", "_gorilla_csrf="+csrf.Token(r))
templates.ExecuteTemplate(w, "<template_here>", nil)
}
func doLogin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Set-Cookie", "_gorilla_csrf="+csrf.Token(r))
/**
builds resp
**/
w.Write(resp)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/login", showLoginPage).Methods("GET")
r.HandleFunc("/login", doLogin).Methods("POST")
r.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("./js"))))
r.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("./css"))))
srv := &http.Server{
Handler: csrf.Protect([]byte("very-secret-string"), csrf.Secure(false))(r),
Addr: "127.0.0.1:8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
`
然而,在我的前端,我有这个,以便所有请求得到更新: `
var getCookie = function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
};
$.ajaxPrefilter(function( options ) {
options.beforeSend = function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', getCookie('_gorilla_csrf'));
}
});
`
我知道我必须遗漏一些东西,但我真的根本无法理解这一点。任何帮助都将非常感激。
答案 0 :(得分:1)
您似乎正在使用此行覆盖大猩猩创建的真实CSRF令牌。 Gorilla正在使用会话存储来保存真正的CSRF令牌以进行验证。
// list of models, because you want ALL of them
var managementModels = new List<CollectionsManagementViewModel>();
var setupIds = _repository.GetAllYearSetupIds();
foreach(var setupId in setupIds)
{
// new model created for each setup id
var managementModel = _repository.GetOverdueBalances(page, pageLength,
setupId.YearSetupId, balancefilter,
sort, direction == Constants.ascending,
spreadsheetType);
managementModel.Title = title + " Management";
managementModels.Add(managementModel); // add model to list
}
// pass collection to view
return View("CollectionsManagement", managementModels);
请勿触摸w.Header().Set("Set-Cookie", "_gorilla_csrf="+csrf.Token(r))
此Cookie。
Gorilla仅通过_gorilla_csrf
和form field
支持CSRF。因此,选择他们的this post所需的信息(表单字段,标题和自定义字段名称和标题名称)。
header
按此顺序检查CSRF令牌:
gorilla / csrf在后续的POST / PUT / PATCH / DELETE /等中检查HTTP头(第一个)和form body(第二个)。请求令牌。