Jwt-token Authentication practice in GO-Zero
You need to read this article before you read it
Golden Gorm V2+ suitable for entrepreneurship golang micro-services framework GO-Zero combat
Create a project
Generate the go.mod file
Create the project with the following instructions
mkdir jwttoken
cd jwttoken
go mod init jwttoken
Copy the code
Define user. API
The API is designed as follows
describe | format | methods | parameter | return | Whether authentication is required |
---|---|---|---|---|---|
The user login | /open/authorization | post | Mobile: mobile phone number,passwd: password,code: image verification code | Id: indicates the user ID. Token: indicates the user token | no |
Updating User Information | /user/update | post | Mobile: indicates the user’s mobile phone number | Token: indicates the new token of the user | is |
According to the above description, the template file for writing the API is as follows
type (
UserOptReq struct {
mobile string `form:"mobile"`
passwd string `form:"passwd"`
code string `form:"code,optional"`
}
UserOptResp struct {
id uint `json:"id"`
token string `json:"token"`
}
/ / modify
UserUpdateReq struct {
id uint `form:"id"`
mobile string `form:"mobile,optional"`
}
)
service user-api {
@server(
handler: authorizationHandler
folder: open
)
post /open/authorization(UserOptReq) returns(UserOptResp)
@server(
handler: edituserHandler
folder: user
)
post /user/update(UserUpdateReq) returns(UserOptResp)
}
Copy the code
Pay attention to
- There can only be one service in a file
- The tool will eventually generate various structures using the model in Type as the template, so the parameters should be consistent with the structure
- If we need to manage business by folder, we can define the Folder property
The generated code
Use the following instructions to generate the code
goctl api go -api user.api -dir .
Copy the code
Run the
go run open.go
Copy the code
Test the
The curl http://127.0.0.1:8888/open/authorization - X POST - d"mobile=15367151352&passwd=123rte&code=asasa"\"passwd\":\"testpwd\",\"code\":\"asdf\"}
{"id": 0."token":""}
Copy the code
Middleware implements authentication
Create auth.go file under handler. The key code is as follows
// Authentication whitelist, where authentication is not required
var whiteList []string = []string{
"/open/",}// Authentication middleware
func Auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware"."auth")
uri := r.RequestURI
// Default is not present
isInWhiteList := false
// Determine whether the request contains elements from the whitelist
for _, v := range whiteList {
if strings.Contains(uri, v) {
isInWhiteList = true}}// If you love whitelist inside directly pass
if isInWhiteList {
next(w, r)
return
}
// Get the x-token field in the header
token := r.Header.Get("X-Token")
// See util\ jwttok.go for the utility class
_, err := utils.DecodeJwtToken(token)
// Return error if there is an error
iferr ! =nil {
httpx.Error(w, err)
return
}
// Continue without error
next(w, r)
}
}
Copy the code
Add a line of code to phones. go
func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) {
// Add this line
engine.Use(Auth)
/ / /.
}
Copy the code
Generate jwttoken
Jwttoken is obtained in Logic \ Open \ authorizationLogic.go
func (l *AuthorizationLogic) Authorization(req types.UserOptReq) (*types.UserOptResp, error) {
// This is the utility class that generates jwTToken
token, err := utils.EncodeJwtToken(map[string]interface{} {"role": "kefu"."id": "10086",})return &types.UserOptResp{
Token: token,
}, err
}
Copy the code
test
Access when no token is carried
> curl http://127.0.0.1:8888/user/update - X POST - d"mobile=15367151352&id=123"Authentication failed and authentication parameters were missing. ProcedureCopy the code
Access token
> curl http://127.0.0.1:8081/open/authorization - X POST - d"mobile=15367151352&passwd=123rte&code=asasa"
{"id": 1599063149,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTkzMjIzNDksImlkIjoiMTUzNjcxNTEzNTIifQ.jcdg3c2rdigPO5ZTxcDilVGERAuMIdY 9BUmMNX3ZA9c"}
Copy the code
Access when carrying a token
> curl http://127.0.0.1:8888/user/update - POST - H X"X-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTkzMjIzNDksImlkIjoiMTUzNjcxNTEzNTIifQ.jcdg3c2rdigPO5ZTxcDilVGERAuMIdY9 BUmMNX3ZA9c" -d "mobile=15367151352&id=123"
# request successful
{"id": 123,"token":""}
Copy the code
Access with incorrect token
> curl http://127.0.0.1:8888/user/update - POST - H X"X-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTkzMjIzNDksImlkIjoiMTUzNjcxNTEzNTIifQ.jcdg3c2rdigPO5ZTxcDilVGERAuMIdY9 BUmMNX3ZA9c0000" -d "mobile=15367151352&id=123"
Invalid signature returned
signature is invalid
Copy the code
Code acquisition for this article
Follow the public account betaidea input JWT to get follow the public account Betaidea input goZero to goZero entry code
Spread the word
Send benefits to uniAPP users Gospel is coming! After hundreds of thousands of users, our customer service system is finally available. Are you still worried about mall access to customer service? Just one line of code to access!! Just one line of code!!!!
/*kefu.vue*/
<template>
<view>
<IdeaKefu :siteid="siteId" ></IdeaKefu>
</view>
</template>
<script>
import IdeaKefu from "@/components/idea-kefu/idea-kefu.vue"
export default {
components:{
IdeaKefu
},
data() {
return {
siteId:2}}}Copy the code
The effect is great
Address kefu.techidea8.com/html/wiki/ development document