Golang 中的微服務-第 4 部分-使用 JWT 做認證

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。在之前的文章裡,我們建立了一個使用者服務,儲存了一些使用者。現在我們看下如何在使用者服務中安全的儲存使用者密碼,同時,通過微服務寫幾個功能,來驗證使用者,發布安全性權杖。注意,我現在已經把我們的服務拆分到幾個不同的倉庫裡。 我覺得這樣部署起來容易些。 最開始我打算做成一個單獨的倉庫,但是發現用 Go 的 dep 管理有點麻煩,有很多衝突。我也會說明下如何獨立地運行和測試微服務。遺憾的是,用這種方法我們就不能用 docker-compose 了。 不過目前用起來還不錯。如果你在這方面有什麼建議,可以[給我發郵件](ewan.valentine89@gmail.com)!現在你要手動啟動資料庫:```$ docker run -d -p 5432:5432 postgres$ docker run -d -p 27017:27017 mongo```最新的倉庫地址在下面:- [https://github.com/EwanValentine/shippy-consignment-service]( https://github.com/EwanValentine/shippy-consignment-service)- [https://github.com/EwanValentine/shippy-user-service](https://github.com/EwanValentine/shippy-user-service)- [https://github.com/EwanValentine/shippy-vessel-service](https://github.com/EwanValentine/shippy-vessel-service)- [https://github.com/EwanValentine/shippy-user-cli](https://github.com/EwanValentine/shippy-user-cli)- [https://github.com/EwanValentine/shippy-consignment-cli](https://github.com/EwanValentine/shippy-consignment-cli)首先,我們要更新下 handler 檔案,做密碼雜湊,這是非常必要的。絕對不能,也堅決不要使用純文字密碼。你們可能會想 ‘廢話,那還用說麼’ ,但我還要堅持強調下!```go// shippy-user-service/handler.go... func (srv *service) Auth(ctx context.Context, req *pb.User, res *pb.Token) error {log.Println("Logging in with:", req.Email, req.Password)user, err := srv.repo.GetByEmail(req.Email)log.Println(user)if err != nil {return err}// Compares our given password against the hashed password// stored in the databaseif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {return err}token, err := srv.tokenService.Encode(user)if err != nil {return err}res.Token = tokenreturn nil}func (srv *service) Create(ctx context.Context, req *pb.User, res *pb.Response) error {// Generates a hashed version of our passwordhashedPass, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)if err != nil {return err}req.Password = string(hashedPass)if err := srv.repo.Create(req); err != nil {return err}res.User = reqreturn nil}```這裡沒做太多改動,除了增加了密碼雜湊功能,我們在儲存新使用者之前把雜湊後的內容作為新的密碼。同樣的,在認證部分,我們會校正密碼的雜湊值。現在我們能夠安全的認證資料庫裡的使用者資訊,我們需要一個機制,能使用介面和分布式服務來做認證。實現這樣的功能有許多方法,但是我發現,能通過服務和 web 使用的最簡單的認證方法是用 [JWT](https://jwt.io/)。不過在我們繼續下面的內容之前,請查看下我在每個服務中的 Dockfiles 和 Makefiles 做的修改。為了匹配最新的 git 倉庫,我也修改了 imports 。## JWT[JWT](https://jwt.io/) 是 JSON web tokens 的縮寫,是一個分布式的安全性通訊協定。類似 OAuth。 概念很簡單,用演算法給使用者產生一個唯一的雜湊,這個雜湊值可以用來比較和校正。不僅如此,token 自身也會包含使用者的中繼資料 (metadata)。也就是說,使用者資料本身也可以是 token 的一部分。 我們看一個 JWT 的執行個體:```eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ```token 被 '.' 分成三部分。每個部分都有各自的含義。第一部分是 token 自身的中繼資料,像 token 的類型,建立 token 使用的演算法等。讓用戶端能知道怎麼給 token 解碼。第二部分是使用者自訂的中繼資料。可以是你的使用者詳情,到期時間,任何你想填的內容。最後一個部分是認證簽名,包括用什麼方法,什麼資料給 token 做雜湊這類資訊。當然用 JWT 也有缺點和使用風險,這些缺點在 [這篇文章](http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/) 中總結的很好。同時,我推薦大家讀 [這篇文章](https://www.owasp.org/index.php/JSON_Web_Token_(JWT)_Cheat_Sheet_for_Java),這裡有安全層面上的最佳實務方法。有一點我想要大家特別注意下,就是擷取使用者的源 IP,並用它作為令牌聲明的一部分。這樣可以確保沒有人能盜取你的令牌,並在另一台機器上偽裝成你。確保使用 https,減少這種類型的攻擊,因為使用 https 能保護你的 token,免受中間人攻擊。用來做 JWT 雜湊的演算法有很多,大體分為兩類。對稱式加密和非對稱式加密。對稱式加密類似我們現在用的方式,使用共用鹽值 (salt)。非對稱式加密會在用戶端和服務端分別使用公開金鑰和私密金鑰。用來在多個服務之間做認證是極好的。更多資源:- [Auth0](https://auth0.com/blog/json-web-token-signing-algorithms-overview/)- [RFC spec for algorithms](https://tools.ietf.org/html/rfc7518#section-3)現在我們知道 JWT 的基本概念了。我們更新下 `token_service.go` 實現這些操作。我們可以用這個 Go 的庫 `github.com/dgrijalva/jwt-go` ,這個庫寫的很棒,有很多不錯的執行個體。```go// shippy-user-service/token_service.gopackage mainimport ("time"pb "github.com/EwanValentine/shippy-user-service/proto/user""github.com/dgrijalva/jwt-go")var (// Define a secure key string used// as a salt when hashing our tokens.// Please make your own way more secure than this,// use a randomly generated md5 hash or something.key = []byte("mySuperSecretKeyLol"))// CustomClaims is our custom metadata, which will be hashed// and sent as the second segment in our JWTtype CustomClaims struct {User *pb.Userjwt.StandardClaims}type Authable interface {Decode(token string) (*CustomClaims, error)Encode(user *pb.User) (string, error)}type TokenService struct {repo Repository}// Decode a token string into a token objectfunc (srv *TokenService) Decode(tokenString string) (*CustomClaims, error) {// Parse the tokentoken, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {return key, nil})// Validate the token and return the custom claimsif claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {return claims, nil} else {return nil, err}}// Encode a claim into a JWTfunc (srv *TokenService) Encode(user *pb.User) (string, error) {expireToken := time.Now().Add(time.Hour * 72).Unix()// Create the Claimsclaims := CustomClaims{user,jwt.StandardClaims{ExpiresAt: expireToken,Issuer: "go.micro.srv.user",},}// Create tokentoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)// Sign token and returnreturn token.SignedString(key)}```照常,我寫了一些注釋解釋了部分細節,不過這裡的導言寫的比較簡單。Decode 方法,是將一個字串 token 解析成一個 token 對象,驗證下,如果有效,則返回一個 CustomClaims 對象。這樣我們能通過這個 CustomClaims 對象擷取到使用者的中繼資料來確認該使用者是否有效。Encode 方法,做的正好相反,將你的自訂的中繼資料,雜湊成一個新的 JWT ,並返回。注意我們在上面設定了一個 'key' 變數,這個 key 是一個安全鹽值(salt),在生產環境下請用一個比這個更安全的鹽值。現在我們有了一個驗證 token 的服務。我們更新下 user-cli,我現在已經把這部分簡化成一個指令碼,因為這之前的 cli 部分的代碼有點問題,我以後再來說這個問題,這個工具就是為了測試用:```go// shippy-user-cli/cli.gopackage mainimport ("log""os"pb "github.com/EwanValentine/shippy-user-service/proto/user"micro "github.com/micro/go-micro"microclient "github.com/micro/go-micro/client""golang.org/x/net/context")func main() {srv := micro.NewService(micro.Name("go.micro.srv.user-cli"),micro.Version("latest"),)// Init will parse the command line flags.srv.Init()client := pb.NewUserServiceClient("go.micro.srv.user", microclient.DefaultClient)name := "Ewan Valentine"email := "ewan.valentine89@gmail.com"password := "test123"company := "BBC"r, err := client.Create(context.TODO(), &pb.User{Name: name,Email: email,Password: password,Company: company,})if err != nil {log.Fatalf("Could not create: %v", err)}log.Printf("Created: %s", r.User.Id)getAll, err := client.GetAll(context.Background(), &pb.Request{})if err != nil {log.Fatalf("Could not list users: %v", err)}for _, v := range getAll.Users {log.Println(v)}authResponse, err := client.Auth(context.TODO(), &pb.User{Email: email,Password: password,})if err != nil {log.Fatalf("Could not authenticate user: %s error: %v\n", email, err)}log.Printf("Your access token is: %s \n", authResponse.Token)// let's just exit becauseos.Exit(0)}```目前我們有一些硬式編碼值,替換下這些值,然後用 `$make build && make run` 執行指令碼。你可以看到返回了一個 token。把這個長長的 token 值拷貝下,你馬上就會用到!現在我們更新下我們的 consignment-cli,產生一個 token 字串,傳給 consignment-service:```go// shippy-consignment-cli/cli.go...func main() {cmd.Init()// Create new greeter clientclient := pb.NewShippingServiceClient("go.micro.srv.consignment", microclient.DefaultClient)// Contact the server and print out its response.file := defaultFilenamevar token stringlog.Println(os.Args)if len(os.Args) < 3 {log.Fatal(errors.New("Not enough arguments, expecing file and token."))}file = os.Args[1]token = os.Args[2]consignment, err := parseFile(file)if err != nil {log.Fatalf("Could not parse file: %v", err)}// Create a new context which contains our given token.// This same context will be passed into both the calls we make// to our consignment-service.ctx := metadata.NewContext(context.Background(), map[string]string{"token": token,})// First call using our tokenised contextr, err := client.CreateConsignment(ctx, consignment)if err != nil {log.Fatalf("Could not create: %v", err)}log.Printf("Created: %t", r.Created)// Second callgetAll, err := client.GetConsignments(ctx, &pb.GetRequest{})if err != nil {log.Fatalf("Could not list consignments: %v", err)}for _, v := range getAll.Consignments {log.Println(v)}}```現在我們更新 consignment-service 來核對一下擷取 token 的請求,並傳給 user-service :```go// shippy-consignment-service/main.gofunc main() {... // Create a new service. Optionally include some options here.srv := micro.NewService(// This name must match the package name given in your protobuf definitionmicro.Name("go.micro.srv.consignment"),micro.Version("latest"),// Our auth middlewaremicro.WrapHandler(AuthWrapper),)...}... // AuthWrapper is a high-order function which takes a HandlerFunc// and returns a function, which takes a context, request and response interface.// The token is extracted from the context set in our consignment-cli, that// token is then sent over to the user service to be validated.// If valid, the call is passed along to the handler. If not,// an error is returned.func AuthWrapper(fn server.HandlerFunc) server.HandlerFunc {return func(ctx context.Context, req server.Request, resp interface{}) error {meta, ok := metadata.FromContext(ctx)if !ok {return errors.New("no auth meta-data found in request")}// Note this is now uppercase (not entirely sure why this is...)token := meta["Token"]log.Println("Authenticating with token: ", token)// Auth hereauthClient := userService.NewUserServiceClient("go.micro.srv.user", client.DefaultClient)_, err := authClient.ValidateToken(context.Background(), &userService.Token{Token: token,})if err != nil {return err}err = fn(ctx, req, resp)return err}}```然後我們執行 consignment-cli工具,cd 到新的 shippy-consignment-cli 倉庫,執行 `$make build` 來建立新的 docker 鏡像, 現在運行:```$ make build$ docker run --net="host" \ -e MICRO_REGISTRY=mdns \ consignment-cli consignment.json \ <TOKEN_HERE>```注意下我們在運行 docker 容器的時候使用了 `--net="host"` 標記。用來告訴 Docker 在本地區域網路來運行我們的容器,如127.0.0.1 或 localhost,而不是 Docker 的內網。注意,用這個方法不需要使用連接埠轉寄。因此只需要用 -p 8080 代替 -p 8080:8080 就可以了。 [更多關於 Docker 網路的內容請看這裡](https://docs.docker.com/engine/userguide/networking/)。到這一步,你就能看到新的 consignment 被建立了。試著從 token 裡刪除幾個字母,token 就會變無效。會出現錯誤。好了,現在我們建立了一個 JWT token 的服務,和一個用來驗證 JWT token 的中介軟體,而 JWT token 用來驗證使用者。如果你不想用 go-micro,而是 vanilla grpc,你的中介軟體是類似這樣的:```gofunc main() {myServer := grpc.NewServer(grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(AuthInterceptor),)}func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {// Set up a connection to the server.conn, err := grpc.Dial(authAddress, grpc.WithInsecure())if err != nil {log.Fatalf("did not connect: %v", err)}defer conn.Close()c := pb.NewAuthClient(conn)r, err := c.ValidateToken(ctx, &pb.ValidateToken{Token: token})if err != nil {log.Fatalf("could not authenticate: %v", err)}return handler(ctx, req)}```這個設定在本地運行有點不靈活。但是我們並不總在本地運行每一個服務。我們建立的服務應該互相獨立,能單獨測試。現在的情況下,如果我們只需要測試 consignment-service,就不需要啟動 auth-service。因此我在這加了一個開關,開啟或關閉其他的服務。我更新 consignment-service 裡的 auth 封裝:```go// shippy-user-service/main.gofunc AuthWrapper(fn server.HandlerFunc) server.HandlerFunc {return func(ctx context.Context, req server.Request, resp interface{}) error {// This skips our auth check if DISABLE_AUTH is set to trueif os.Getenv("DISABLE_AUTH") == "true" {return fn(ctx, req, resp)}}}```然後在 Makefile 裡加個開關:```// shippy-user-service/Makefilerun:docker run -d --net="host" \-p 50052 \-e MICRO_SERVER_ADDRESS=:50052 \-e MICRO_REGISTRY=mdns \-e DISABLE_AUTH=true \consignment-service```用這個方式,在本地運行微服務中的某個部分,會更簡單,解決這個問題還有幾個不同的方法,但是我認為這個最簡單。希望你覺得有點協助,儘管在方向上有小改動。同時,如果你對使用單個倉庫運行微服務這方面有什麼建議,非常歡迎告知我,那麼這部分內容就簡單多了。如果你發現這篇文章裡有任何 bug,錯誤,或者你有對這篇文章有任何反饋或者有協助的建議,[請給我發郵件](ewan.valentine89@gmail.com)。如果你覺得這個系列文章有用,而且你用了廣告過濾(俺沒怪你)。請考慮打賞下我的辛苦勞動噢。非常感謝!。[https://monzo.me/ewanvalentine](https://monzo.me/ewanvalentine)

via: https://ewanvalentine.io/microservices-in-golang-part-4

作者:André Carvalho 譯者:ArisAries 校對:polaris1119

本文由 GCTT 原創編譯,Go語言中文網 榮譽推出

本文由 GCTT 原創翻譯,Go語言中文網 首發。也想加入譯者行列,為開源做一些自己的貢獻嗎?歡迎加入 GCTT!
翻譯工作和譯文發表僅用於學習和交流目的,翻譯工作遵照 CC-BY-NC-SA 協議規定,如果我們的工作有侵犯到您的權益,請及時聯絡我們。

歡迎遵照 CC-BY-NC-SA 協議規定 轉載,敬請在本文中標註並保留原文/譯文連結和作者/譯者等資訊。
文章僅代表作者的知識和看法,如有不同觀點,請樓下排隊吐槽

1528 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.