当前位置:网站首页>Gin security -3: fast implementation of CSRF verification
Gin security -3: fast implementation of CSRF verification
2022-06-23 21:06: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 do you have
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/gin
Quick start
1. establish boot.yaml
boot.yaml The file will tell rk-boot How to start Gin 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 .
---
gin:
- name: greeter # Required
port: 8080 # Required
enabled: true # Required
interceptors:
csrf:
enabled: true # Optional, default: false2. establish main.go
We are Gin Add two Restful API.
- GET /v1/greeter: Returns the generated by the server CSRF Token
- POST /v1/greeter: 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/gin-gonic/gin"
"github.com/rookie-ninja/rk-boot"
"github.com/rookie-ninja/rk-boot/gin"
"net/http"
)
// Application entrance.
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
ginEntry := rkbootgin.GetGinEntry("greeter")
// Register /v1/greeter GET
ginEntry.Router.GET("/v1/greeter", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "Hello!")
})
// Register /v1/greeter POST
ginEntry.Router.POST("/v1/greeter", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "Hello!")
})
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}3. Folder structure
. ├── boot.yaml ├── go.mod ├── go.sum └── main.go 0 directories, 4 files
- go.mod
module github.com/rookie-ninja/rk-demo go 1.16 require ( github.com/rookie-ninja/rk-boot v1.4.0 github.com/rookie-ninja/rk-boot/gin v1.2.12 )
4. verification
- send out GET Ask to /v1/greeter, We will get CSRF Token.
$ curl -X GET -vs localhost:8080/v1/greeter ... < HTTP/1.1 200 OK < Content-Type: application/json; charset=utf-8 < Set-Cookie: _csrf=XVlBzgbaiCMRAjWwhTHctcuAxhxKQFDa; Expires=Mon, 27 Dec 2021 09:35:20 GMT < Vary: Cookie < Date: Sun, 26 Dec 2021 09:35:20 GMT < Content-Length: 8 < * Connection #0 to host localhost left intact "Hello!"*
- send out POST Ask to /v1/greeter, 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/greeter ... > Cookie: _csrf=my-test-csrf-token > X-CSRF-Token:my-test-csrf-token > < HTTP/1.1 200 OK < Content-Type: application/json; charset=utf-8 < Set-Cookie: _csrf=my-test-csrf-token; Expires=Mon, 27 Dec 2021 09:35:43 GMT < Vary: Cookie < Date: Sun, 26 Dec 2021 09:35:43 GMT < Content-Length: 8 < * Connection #0 to host localhost left intact "Hello!"*
- send out POST Ask to /v1/greeter, Illegal provision CSRF Token.
$ curl -X POST -v -H "X-CSRF-Token:my-test-csrf-token" localhost:8080/v1/greeter
...
> X-CSRF-Token:my-test-csrf-token
>
< HTTP/1.1 403 Forbidden
< Content-Type: application/json; charset=utf-8
< Date: Sun, 26 Dec 2021 09:36:18 GMT
< Content-Length: 91
<
* 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 |
|---|---|---|---|
gin.interceptors.csrf.enabled | start-up CSRF Interceptor | boolean | false |
gin.interceptors.csrf.tokenLength | Token length | int | 32 |
gin.interceptors.csrf.tokenLookup | Where to get Token, Please refer to the following introduction | string | “header:X-CSRF-Token” |
gin.interceptors.csrf.cookieName | Cookie name | string | _csrf |
gin.interceptors.csrf.cookieDomain | Cookie domain | string | "" |
gin.interceptors.csrf.cookiePath | Cookie path | string | "" |
gin.interceptors.csrf.cookieMaxAge | Cookie MaxAge( second ) | int | 86400 (24 Hours ) |
gin.interceptors.csrf.cookieHttpOnly | Cookie HTTP Only Options | bool | false |
gin.interceptors.csrf.cookieSameSite | Cookie SameSite Options , Support lax, strict, none, default | string | "lax" |
gin.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".
边栏推荐
- Where should DNS start? I -- from the failure of Facebook
- Full instructions for databinding
- [golang] reexamine closures from the perspective of go language
- . Net Core 3. X MVC built-in log extension log4net
- . NET Framework . Net core and Net standard
- How to make a commodity price tag
- Application of JDBC in performance test
- Cloudbase init considerations
- Implementing MySQL fuzzy search with node and express
- Is Guoyuan futures trading software formal? How to download safely?
猜你喜欢

Applet development framework recommendation

FPGA based electromagnetic ultrasonic pulse compression detection system paper + source file
Implementing MySQL fuzzy search with node and express

JS advanced programming version 4: generator learning

3000 frame animation illustrating why MySQL needs binlog, redo log and undo log

Yaokui tower in Fengjie, Chongqing, after its completion, will be the safety tower for Sichuan river shipping with five local scholars in the company
Application of JDBC in performance test
随机推荐
[golang] use go language to operate etcd - configuration center
How to make a material identification sheet
JS delete object attribute
Row height, (top line, middle line, baseline, bottom line), vertical align
How to separate image processing? What should I pay attention to when separating layers?
QPS fails to go up due to frequency limitation of public network CLB bandwidth
How to convert []byte to io. in go Reader?
Dart series: your site is up to you. Use extension to extend classes
数字电路概述
[golang] quick review guide quickreview (VIII) -- goroutine
Talk about leap seconds
How to log in to the server through the fortress machine to transfer files? What are the specific steps?
How to deal with unclear pictures? What are the techniques for taking clear pictures?
More than 1200 phishing kits that can intercept 2fa detected in the field
徽商期货交易软件正规吗?如何安全下载?
Development and code analysis of easycvr national standard user defined streaming address function
. Net Core 3. X MVC built-in log extension log4net
What is the difference between a database and a cloud disk drive? What functions can cloud disk drives achieve?
Troubleshooting of black screen after easynvr is cascaded to the upper platform and played for one minute
How to make a commodity price tag