Skip to content

Commit 530da87

Browse files
committed
Add gRPC client example with Basic auth
1 parent c1255ad commit 530da87

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

examples/grpc_client/main.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"context"
5+
"encoding/base64"
56
"encoding/json"
67
"log"
78
"net"
@@ -12,7 +13,10 @@ import (
1213
utcp "github.com/universal-tool-calling-protocol/go-utcp"
1314
"github.com/universal-tool-calling-protocol/go-utcp/src/grpcpb"
1415
"google.golang.org/grpc"
16+
"google.golang.org/grpc/codes"
17+
"google.golang.org/grpc/metadata"
1518
"google.golang.org/grpc/reflection"
19+
"google.golang.org/grpc/status"
1620
)
1721

1822
type server struct {
@@ -100,12 +104,26 @@ func (s *server) CallTool(ctx context.Context, req *grpcpb.ToolCallRequest) (*gr
100104
return &grpcpb.ToolCallResponse{ResultJson: string(out)}, nil
101105
}
102106

107+
func basicAuthInterceptor(user, pass string) grpc.UnaryServerInterceptor {
108+
expected := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
109+
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
110+
md, ok := metadata.FromIncomingContext(ctx)
111+
if !ok {
112+
return nil, status.Error(codes.Unauthenticated, "missing metadata")
113+
}
114+
if auths := md.Get("authorization"); len(auths) == 0 || auths[0] != expected {
115+
return nil, status.Error(codes.Unauthenticated, "invalid credentials")
116+
}
117+
return handler(ctx, req)
118+
}
119+
}
120+
103121
func startServer(addr string) *grpc.Server {
104122
lis, err := net.Listen("tcp", addr)
105123
if err != nil {
106124
log.Fatalf("listen: %v", err)
107125
}
108-
s := grpc.NewServer()
126+
s := grpc.NewServer(grpc.UnaryInterceptor(basicAuthInterceptor("user", "pass")))
109127
grpcpb.RegisterUTCPServiceServer(s, &server{})
110128
reflection.Register(s)
111129
go s.Serve(lis)

examples/grpc_client/provider.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
"provider_type": "grpc",
55
"name": "grpc",
66
"host": "127.0.0.1",
7-
"port": 9090
7+
"port": 9090,
8+
"auth": {
9+
"auth_type": "basic",
10+
"username": "user",
11+
"password": "pass"
12+
}
813
}
914
]
1015
}

0 commit comments

Comments
 (0)