Auth

Example:auth

For the security, only authorized clients can invoke services.

Clients must set an authorization token which can gets from OAuth/OAuth2 or granted access token.

Servers receive requests, first check the auth token. They reject requests with invalid tokens.

  1. func main() {
  2. flag.Parse()
  3. s := server.NewServer()
  4. s.RegisterName("Arith", new(example.Arith), "")
  5. s.AuthFunc = auth
  6. s.Serve("reuseport", *addr)
  7. }
  8. func auth(ctx context.Context, req *protocol.Message, token string) error {
  9. if token == "bearer tGzv3JOkF0XG5Qx2TlKWIA" {
  10. return nil
  11. }
  12. return errors.New("invalid token")
  13. }

Server must define a AuthFunc to validate auth token. In the above example, only requests with token bearer tGzv3JOkF0XG5Qx2TlKWIA are valid.

Client must set the token:

  1. func main() {
  2. flag.Parse()
  3. d := client.NewPeer2PeerDiscovery("tcp@"+*addr, "")
  4. option := client.DefaultOption
  5. option.ReadTimeout = 10 * time.Second
  6. xclient := client.NewXClient("Arith", client.Failtry, client.RandomSelect, d, option)
  7. defer xclient.Close()
  8. //xclient.Auth("bearer tGzv3JOkF0XG5Qx2TlKWIA")
  9. xclient.Auth("bearer abcdefg1234567")
  10. args := &example.Args{
  11. A: 10,
  12. B: 20,
  13. }
  14. reply := &example.Reply{}
  15. ctx := context.WithValue(context.Background(), share.ReqMetaDataKey, make(map[string]string))
  16. err := xclient.Call(ctx, "Mul", args, reply)
  17. if err != nil {
  18. log.Fatalf("failed to call: %v", err)
  19. }
  20. log.Printf("%d * %d = %d", args.A, args.B, reply.C)
  21. }

Notice: you must set a map[string]string as share.ReqMetaDataKey otherwise it will report an error

By smallnest updated 2018-12-04 11:47:26