main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // The client demonstrates how to supply an OAuth2 token for every RPC.
  19. package main
  20. import (
  21. "context"
  22. "crypto/tls"
  23. "log"
  24. "time"
  25. "golang.org/x/oauth2"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/credentials"
  28. "google.golang.org/grpc/credentials/oauth"
  29. pb "google.golang.org/grpc/examples/helloworld/helloworld"
  30. )
  31. func main() {
  32. perRPC := oauth.NewOauthAccess(fetchToken())
  33. opts := []grpc.DialOption{
  34. // In addition to the following grpc.DialOption, callers may also use
  35. // the grpc.CallOption grpc.PerRPCCredentials with the RPC invocation
  36. // itself.
  37. // See: https://godoc.org/google.golang.org/grpc#PerRPCCredentials
  38. grpc.WithPerRPCCredentials(perRPC),
  39. // oauth.NewOauthAccess requires the configuration of transport
  40. // credentials.
  41. grpc.WithTransportCredentials(
  42. credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}),
  43. ),
  44. }
  45. conn, err := grpc.Dial(":8080", opts...)
  46. if err != nil {
  47. log.Fatalf("did not connect: %v", err)
  48. }
  49. defer conn.Close()
  50. c := pb.NewGreeterClient(conn)
  51. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  52. defer cancel()
  53. r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "authenticated-client"})
  54. if err != nil {
  55. log.Fatalf("could not greet: %v", err)
  56. }
  57. log.Printf("Greeting: %s", r.Message)
  58. }
  59. // fetchToken simulates a token lookup and omits the details of proper token
  60. // acquisition. For examples of how to acquire an OAuth2 token, see:
  61. // https://godoc.org/golang.org/x/oauth2
  62. func fetchToken() *oauth2.Token {
  63. return &oauth2.Token{
  64. AccessToken: "some-secret-token",
  65. }
  66. }