gRPC之双向认证初入

Posted 程序彤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gRPC之双向认证初入相关的知识,希望对你有一定的参考价值。

  1. 生成.pem和.key文件
  2. server.go文件
package main

import (
	"crypto/tls"
	"crypto/x509"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"learnProto/services/proto"
	"net"
)

func main(){
	cert, _ := tls.LoadX509KeyPair("cert/server.pem", "cert/server.key")
	certPool := x509.NewCertPool()
	ca, _ := ioutil.ReadFile("cert/ca.pem")
	certPool.AppendCertsFromPEM(ca)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert}, // 服务端证书
		ClientAuth:   tls.RequireAndVerifyClientCert, // 双向验证
		ClientCAs:    certPool,
	})

	rpcServer := grpc.NewServer(grpc.Creds(creds)) // 传入证书
	//rpcServer := grpc.NewServer() // 传入证书
	proto.RegisterProdServiceServer(rpcServer,new(proto.ProdService))
	//listen, _ := net.Listen("tcp", ":8081")
	//rpcServer.Serve(listen)
	//mux:= http.NewServeMux()
	//mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
	//	fmt.Println(request.Proto)
	//	fmt.Println(request)
	//	rpcServer.ServeHTTP(writer,request)
	//})
	//httpServer := &http.Server{
	//	Addr:    ":8081",
	//	Handler: mux,
	//}
	//httpServer.ListenAndServeTLS("")
	lis, _ := net.Listen("tcp", ":8081")
	rpcServer.Serve(lis)
}

  1. client.go文件
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"learnProto/services/proto"
	"log"
)

func main(){

	cert, _ := tls.LoadX509KeyPair("cert/client.pem", "cert/client.key")
	certPool := x509.NewCertPool()
	ca, _ := ioutil.ReadFile("cert/ca.pem")
	certPool.AppendCertsFromPEM(ca)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert}, // 客户端证书
		ServerName: "localhost", // 域名
		RootCAs: certPool, // 根证书
	})
	conn, err := grpc.Dial(":8081",grpc.WithTransportCredentials(creds)) //grpc.WithInsecure()
	//conn, err := grpc.Dial(":8081",grpc.WithInsecure()) //
	if err!=nil {
		log.Fatal(err)
	}
	defer conn.Close()
	productClient := proto.NewProdServiceClient(conn)
	productRes, err := productClient.GetProdStock(context.Background(), &proto.ProdRequset{
		ProdId: 66,
	})
	if err!=nil{
		log.Fatal(err)
	}
	fmt.Println(productRes.ProdStock)
}

以上是关于gRPC之双向认证初入的主要内容,如果未能解决你的问题,请参考以下文章

java版gRPC实战之五:双向流

java版gRPC实战之五:双向流

gRPC进阶

grpc应用之二 gRPC使用

grpc双向流究竟是什么情况?2段代码告诉你

加密之SSL和单双向认证