当前位置:网站首页>Goframe framework (RK boot): fast implementation of CSRF verification
Goframe framework (RK boot): fast implementation of CSRF verification
2022-06-23 02:27:00 【Trespass 】
Introduce
How does this article describe rk-boot Implement the server CSRF Verification logic .
What is? CSRF?
Cross-site request forgery ( English :Cross-site request forgery), Also known as one-click attack perhaps session riding, Commonly abbreviated as CSRF perhaps XSRF, It is a kind of coercion that users are currently logged in Web An attack method that performs unintended operations on an application .
With cross site scripting (XSS) comparison ,XSS Using the user's trust in the designated website ,CSRF Using the trust of the website to the user's web browser .
What defense methods are there ?
There are several popular defense methods , We use examples to realize 【 Add validation Token】 Defense .
1: Token synchronization mode 2: Check Referer Field 3: Add validation Token
Please visit the following address for a complete tutorial :
install
go get github.com/rookie-ninja/rk-boot/gf
Quick start
1. establish boot.yaml
boot.yaml The file will tell rk-boot How to start gogf/gf service .
In the following YAML In file , We made a statement :
- Turn on CSRF Interceptor , Using default parameters . The interceptor will check the request Header in X-CSRF-Token Value , Judge Token Whether it is right .
---
gf:
- name: greeter # Required
port: 8080 # Required
enabled: true # Required
interceptors:
csrf:
enabled: true # Optional, default: false2. establish main.go
We are gogf/gf Add two Restful API.
- GET /v1/hello: Returns the generated by the server CSRF Token
- POST /v1/hello: verification CSRF Token
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/rookie-ninja/rk-boot"
"github.com/rookie-ninja/rk-boot/gf"
"net/http"
)
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Register handler
entry := rkbootgf.GetGfEntry("greeter")
entry.Server.BindHandler("/v1/hello", hello)
// Bootstrap
boot.Bootstrap(context.TODO())
boot.WaitForShutdownSig(context.TODO())
}
func hello(ctx *ghttp.Request) {
ctx.Response.WriteHeader(http.StatusOK)
ctx.Response.WriteJson(map[string]string{
"message": "hello!",
})
}3. Folder structure
. ├── boot.yaml ├── go.mod ├── go.sum └── main.go 0 directories, 4 files
4. start-up main.go
$ go run main.go
2022-02-07T15:02:03.187+0800 INFO boot/gf_entry.go:600 Bootstrap gfEntry {"eventId": "8238e90e-5cd0-4da7-9f9b-7bb9b1946978", "entryName": "greeter", "entryType": "GoFrame"}
------------------------------------------------------------------------
endTime=2022-02-07T15:02:03.188021+08:00
startTime=2022-02-07T15:02:03.187943+08:00
elapsedNano=78089
timezone=CST
ids={"eventId":"8238e90e-5cd0-4da7-9f9b-7bb9b1946978"}
app={"appName":"rk","appVersion":"","entryName":"greeter","entryType":"GoFrame"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}
payloads={"gfPort":8080}
counters={}
pairs={}
timing={}
remoteAddr=localhost
operation=Bootstrap
resCode=OK
eventStatus=Ended
EOE5. verification
- send out GET Ask to /v1/hello, We will get CSRF Token.
$ curl -X GET -vs localhost:8080/v1/hello
...
> Cookie: _csrf=my-test-csrf-token
> X-CSRF-Token:my-test-csrf-token
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Server: GoFrame HTTP Server
< Set-Cookie: _csrf=my-test-csrf-token; Expires=Tue, 08 Feb 2022 07:02:45 GMT
< Trace-Id: 104af099fb6ed11600722376ab2d8a82
< Vary: Cookie
< Date: Mon, 07 Feb 2022 07:02:45 GMT
< Content-Length: 20
<
* Connection #0 to host localhost left intact
{"message":"hello!"}- send out POST Ask to /v1/hello, Provide legal CSRF Token.
$ curl -X POST -v --cookie "_csrf=my-test-csrf-token" -H "X-CSRF-Token:my-test-csrf-token" localhost:8080/v1/hello
...
> Cookie: _csrf=my-test-csrf-token
> X-CSRF-Token:my-test-csrf-token
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Server: GoFrame HTTP Server
< Set-Cookie: _csrf=my-test-csrf-token; Expires=Tue, 08 Feb 2022 07:03:31 GMT
< Trace-Id: 90ded13e066fd1160172237663ed8fbb
< Vary: Cookie
< Date: Mon, 07 Feb 2022 07:03:31 GMT
< Content-Length: 20
<
* Connection #0 to host localhost left intact
{"message":"hello!"}- send out POST Ask to /v1/hello, Illegal provision CSRF Token.
$ curl -X POST -v -H "X-CSRF-Token:my-test-csrf-token" localhost:8080/v1/hello
...
> X-CSRF-Token:my-test-csrf-token
>
< HTTP/1.1 403 Forbidden
< Server: GoFrame HTTP Server
< Trace-Id: c88c53630b6fd116027223761a59ee69
< Date: Mon, 07 Feb 2022 07:03:53 GMT
< Content-Length: 91
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
{"error":{"code":403,"status":"Forbidden","message":"invalid csrf token","details":[null]}}*CSRF Interceptor options
rk-boot A number of CSRF Interceptor options , Unless there is a special need , The override option is not recommended .
Options | describe | type | The default value is |
|---|---|---|---|
gf.interceptors.csrf.enabled | start-up CSRF Interceptor | boolean | false |
gf.interceptors.csrf.tokenLength | Token length | int | 32 |
gf.interceptors.csrf.tokenLookup | Where to get Token, Please refer to the following introduction | string | “header:X-CSRF-Token” |
gf.interceptors.csrf.cookieName | Cookie name | string | _csrf |
gf.interceptors.csrf.cookieDomain | Cookie domain | string | "" |
gf.interceptors.csrf.cookiePath | Cookie path | string | "" |
gf.interceptors.csrf.cookieMaxAge | Cookie MaxAge( second ) | int | 86400 (24 Hours ) |
gf.interceptors.csrf.cookieHttpOnly | Cookie HTTP Only Options | bool | false |
gf.interceptors.csrf.cookieSameSite | Cookie SameSite Options , Support lax, strict, none, default | string | "lax" |
gf.interceptors.csrf.ignorePrefix | Ignore CSRF Verified Restful API Path | []string | [] |
tokenLookup Format
At present, the following three methods are supported , The interceptor will use one of the following methods , Look for... In the request Token.
- from HTTP Header In order to get
- from HTTP Form In order to get
- from HTTP Query In order to get
// Optional. Default value "header:X-CSRF-Token". // Possible values: // - "header:<name>" // - "form:<name>" // - "query:<name>" // Optional. Default value "header:X-CSRF-Token".
边栏推荐
- Circuit analysis (circuit principle)
- Exploit format string vulnerability in CDE
- Unity official case nightmare shooter development summary < I > realization of the role's attack function
- JS request path console reports an error failed to launch 'xxx' because the scheme does not have a registered handler
- [CodeWars] Convert Decimal Degrees to Degrees, Minutes, Seconds
- Gorilla/mux framework (RK boot): add swagger UI
- Information theory and coding
- Rebirth -- C language and the story I have to tell (text)
- 5g spectrum
- What is ISBN code and how to make it
猜你喜欢

How to design API return codes (error codes)?

pd. read_ CSV and np Differences between loadtext

Third order magic cube formula

CSDN browser assistant for online translation, calculation, learning and removal of all advertisements

Performance testing -- Interpretation and practice of 16 enterprise level project framework

My good brother gave me a difficult problem: retry mechanism
![Buuctf misc-[actf freshman competition 2020]outline](/img/a4/ac9d14a69e0759d1e7c65740415bf7.jpg)
Buuctf misc-[actf freshman competition 2020]outline

Interviewer: what is the difference between SSH and SSM frameworks? How to choose??
![Buuctf misc-[bjdctf2020] Nani](/img/4e/ac6bf2f64cb68136581814da73db66.jpg)
Buuctf misc-[bjdctf2020] Nani

1. Mx6u bare metal program (1) - Lighting master
随机推荐
What is a smart farm?
Automatically update site statistics with actions
Hypervisor Necromancy; Recover kernel protector (2)
JS case: support canvas electronic signature function on PC and mobile
Microservice Optimization: internal communication of microservices using grpc
Pychart installation instructions
Using mock data in vite projects -vite plugin mock
Freshman C language summary post (hold change) Part 2 formatted monthly calendar
How to set up an H5 demo of easyplayer locally to play h265 video streams?
Learning notes of recommendation system (1) - Collaborative Filtering - Theory
Log a log4j2 vulnerability handling
Anaconda creates a new environment encounter pit
Campus network AC authentication failed
Pywebio to quickly build web applications
JS request path console reports an error failed to launch 'xxx' because the scheme does not have a registered handler
My good brother gave me a difficult problem: retry mechanism
OVS port traffic statistics practice
Get the structure of the class through reflection, little chestnut
This monitoring tool is enough for the operation and maintenance of small and medium-sized enterprises - wgcloud
2021-11-11