grpc鉴权

服务端 自定义认证 // 注册interceptor
var interceptor grpc.StreamServerInterceptor
interceptor = func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
{
err := auth(s.authClient, ss.Context())
if err != nil {
return err
}
err := handler(srv, ss)
return err
}
opts = append(opts, grpc.StreamInterceptor(interceptor))
TLS认证 cert, err := tls.X509KeyPair([]byte(serverTLSCert), []byte(serverTLSKey))
if err != nil {
【grpc鉴权】log.Logger().Fatal("create tls failed!")
return
}
creds := credentials.NewServerTLSFromCert(&cert)
opts = append(opts, grpc.Creds(creds))
客户端 自定义认证 // customCredential 自定义认证
type customCredential struct{}

// GetRequestMetadata 实现自定义认证接口
func (c customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {

}

// RequireTransportSecurity 自定义认证是否开启TLS
func (c customCredential) RequireTransportSecurity() bool {

}
// 指定自定义认证
opts = append(opts, grpc.WithPerRPCCredentials(new(customCredential)))

tls认证creds, err := credentials.NewClientTLSFromFile("audio/certificate2.crt", "")
if err != nil { grpclog.Fatalf("Failed to create TLS credentials %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))




    推荐阅读