证书制作
openssl genrsa -out server.key 2048
openssl req -new -x509 -sha256 -key server.key -out server.pem -days 3650
代码
https://github.com/fengchunjian/goexamples/tree/master/grpc/tls
描述文件
//proto/hello.proto
syntax = "proto3"; //指定proto版本
package proto; //指定包名
//定义Hello服务
service Hello {
//定义SayHello方法
rpc SayHello(HelloRequest) returns (HelloReply) {}
}
//HelloRequest请求结构
message HelloRequest {
string name = 1;
}
//HelloReply响应结构
message HelloReply {
string message = 1;
}
protoc -I . --go_out=plugins=grpc:. ./hello.proto
服务端
//server/server.go
package main
import (
pb "github.com/fengchunjian/goexamples/grpc/tls/proto" //引入编译生成的包
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials" //引入grpc认证包
"log"
"net"
)
const (
// gRPC服务地址
Address = "127.0.0.1:50052"
)
//定义helloService并实现约定的接口
type helloService struct{}
func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
resp := new(pb.HelloReply)
resp.Message = "Hello " + in.Name + "."
return resp, nil
}
var HelloService = helloService{}
func main() {
listen, err := net.Listen("tcp", Address)
if err != nil {
log.Fatalf("failed to listen:%v", err)
}
//TLS认证
creds, err := credentials.NewServerTLSFromFile("../keys/server.pem", "../keys/server.key")
if err != nil {
log.Fatalf("failed to generate credentials %v", err)
}
s := grpc.NewServer(grpc.Creds(creds)) //实例化grpc Server,并开启TLS认证
pb.RegisterHelloServer(s, HelloService) //注册HelloService
log.Println("Listen on " + Address + " with TLS")
s.Serve(listen)
}
客户端
//client/client.go
package main
import (
pb "github.com/fengchunjian/goexamples/grpc/tls/proto" //引入proto包
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"log"
)
const (
Address = "127.0.0.1:50052"
)
func main() {
//TLS连接
creds, err := credentials.NewClientTLSFromFile("../keys/server.pem", "server name")
if err != nil {
log.Fatalf("Failed to create TLS credentials %v", err)
}
conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
c := pb.NewHelloClient(conn)
reqBody := new(pb.HelloRequest)
reqBody.Name = "gRPC"
r, err := c.SayHello(context.Background(), reqBody)
if err != nil {
log.Fatalln(err)
}
log.Println(r.Message)
}
参考文档
Golang gRPC实践 连载四 gRPC认证
https://segmentfault.com/a/1190000007933303