当前位置:网站首页>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: false

2. 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
EOE

5. 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".
原网站

版权声明
本文为[Trespass ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202071546378217.html