2
头图

We use a series to explain the complete practice of microservices from requirements to online, from code to k8s deployment, from logging to monitoring, etc.

The whole project uses microservices developed by go-zero, which basically includes go-zero and some middleware developed by related go-zero authors. The technology stack used is basically the self-developed components of the go-zero project team, basically go -zero the whole family bucket.

Actual project address: https://github.com/Mikaelemmmm/go-zero-looklook

1. Authentication service

1.1 identity-api

Identity is mainly used for authentication services, which we mentioned earlier in our nginx gateway. When accessing a resource, nginx will first come to identity-api to parse the token, and identity-api will request identity-rpc. All verification and issuance of tokens are unified in identity-rpc.

We will get the token from the Authorization of the header and the accessed resource path from x-Original-Uri

  • If the currently accessed route requires login:

    • Token parsing failed: it will return to the front-end http401 error code;
    • The token parsing is successful: the parsed userId will be put into the x-user of the header and returned to the auth module, and the auth module will pass the header to the corresponding access service (usercenter), so that we can get the login directly in the usercenter user's id
  • If the currently accessed route does not require login:

    • The token is passed in the front-end header

      • If token verification fails: return http401;
      • If the token verification is successful: the parsed userId will be put into the x-user of the header and returned to the auth module, and the auth module will pass the header to the corresponding access service (usercenter), so that we can get it directly in the usercenter The id of the logged in user
    • The token is not passed in the front-end header: userid will pass 0 to the back-end service

The urlNoAuth method determines whether the current resource is configured in yml and can not log in

 //当前url是否需要授权验证
func (l *TokenLogic) urlNoAuth(path string) bool {
   for _, val := range l.svcCtx.Config.NoAuthUrls {
      if val == path {
         return true
      }
   }
   return false
}

The isPass method is to go to identity-rpc to verify the token, mainly using the jwt method of go-zero

1.2 identity-rpc

When we register and log in successfully, the user service will call identity-rpc to generate tokens, so we issue and verify tokens in identity-rpc uniformly, so that each service does not need to write a jwt for maintenance.

When the identity-api request comes in, the identity-api itself can parse out the userid, but if we want to check whether the token is expired, we need to go to the redis in the back-end rpc for secondary verification (of course, if you think there are too many here) For one request, you can put this step into the api to request redis directly), and it is verified by the validateToken method of rpc

 message ValidateTokenReq {
  int64 userId = 1;
  string token = 2;
}
message ValidateTokenResp {
  bool ok = 1;
}

rpc validateToken(ValidateTokenReq) returns(ValidateTokenResp);

Verify that the tokens issued and stored in redis during the previous login, registration and other authorizations are correct and expired.

In this way, the api can return to nginx's auth module whether it fails. If it fails, auth will directly return to the front-end http code 401 (so your front-end should first judge that the http status code >= 400 is all abnormal, and then judge the business error code), if successful Direct access to the back-end service, get the data and return it directly to the front-end display

2. Install goctl and protoc, protoc-gen-go

[Note] This has nothing to do with authentication, but it is used to write the code later. It is best to install it here.

2.1 Install goctl

 # for Go 1.15 and earlier
GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/zeromicro/go-zero/tools/goctl@latest

# for Go 1.16 and later
GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest

Verify that the installation was successful

 $ goctl --version

Goctl custom template template: copy the contents of the data/goctl folder in the project directory to .goctl in the HOME directory, goctl will give priority to the content of this template when generating code

 $ cp -r data/goctl ~/.goctl

2.2 Install protoc

Link: https://github.com/protocolbuffers/protobuf/releases

Directly find the protoc of the corresponding platform, I am a mac intel chip, so find the protoc-3.19.3-osx-x86_64.zip directly, decompress it and enter the bin directory under the directory, and copy the protoc directly to your gopath/bin under the directory.

Verify that the installation was successful

 $ protoc --version

2.3 Install protoc-gen-go

 $ GOPROXY=https://goproxy.cn/,direct go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

Check if there is protoc-gen-go under $GOPATH/bin

[Note]: If you encounter the following problems when using goctl to generate code later

 protoc  --proto_path=/Users/seven/Developer/goenv/go-zero-looklook/app/usercenter/cmd/rpc/pb usercenter.proto --go_out=plugins=grpc:/Users/seven/Developer/goenv/go-zero-looklook/app/usercenter/cmd/rpc --go_opt=Musercenter.proto=././pb
goctl: generation error: unsupported plugin protoc-gen-go which installed from the following source:
google.golang.org/protobuf/cmd/protoc-gen-go, 
github.com/protocolbuffers/protobuf-go/cmd/protoc-gen-go;

Please replace it by the following command, we recommend to use version before v1.3.5:
go get -u github.com/golang/protobuf/protoc-gen-go
goctl version: 1.3.0 darwin/amd64

direct execution

 $ GOPROXY=https://goproxy.cn/,direct go get -u github.com/golang/protobuf/protoc-gen-go

2.4 Install protoc-gen-go-grpc

 $ GOPROXY=https://goproxy.cn/,direct go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

3. Summary

In general, identity is relatively simple, the whole process is as follows:

The user initiates the request resource -> nginx gateway -> matches the corresponding service module -> auth module -> identity-api -> identity-rpc -> the resource requested by the user

project address

https://github.com/zeromicro/go-zero

Welcome go-zero and star support us!

WeChat exchange group

Follow the official account of " Microservice Practice " and click on the exchange group to get the QR code of the community group.


kevinwan
931 声望3.5k 粉丝

go-zero作者