xoauth2.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package email
  2. /*
  3. xoauth2.go
  4. The XOAUTH2 SASL mechanism used by Gmail and Microsoft for IMAP and SMTP.
  5. go-sasl ships the standard OAUTHBEARER but not XOAUTH2, and Microsoft only
  6. accepts the latter, so it is implemented here.
  7. Initial response: "user=" user ^A "auth=Bearer " token ^A ^A
  8. On failure the server sends a base64 JSON challenge; the client must answer
  9. with an empty response, after which the server sends the tagged failure.
  10. */
  11. import (
  12. "encoding/json"
  13. "fmt"
  14. "github.com/emersion/go-sasl"
  15. )
  16. type xoauth2Client struct {
  17. username string
  18. token string
  19. failure string
  20. }
  21. // newXOAuth2Client returns a SASL client for the XOAUTH2 mechanism.
  22. func newXOAuth2Client(username string, token string) sasl.Client {
  23. return &xoauth2Client{username: username, token: token}
  24. }
  25. func (c *xoauth2Client) Start() (string, []byte, error) {
  26. response := "user=" + c.username + "\x01auth=Bearer " + c.token + "\x01\x01"
  27. return "XOAUTH2", []byte(response), nil
  28. }
  29. func (c *xoauth2Client) Next(challenge []byte) ([]byte, error) {
  30. //The only challenge XOAUTH2 defines is the error document. Remember it
  31. //for a better message and send the empty response the protocol expects.
  32. var detail struct {
  33. Status string `json:"status"`
  34. Schemes string `json:"schemes"`
  35. Scope string `json:"scope"`
  36. }
  37. if err := json.Unmarshal(challenge, &detail); err == nil && detail.Status != "" {
  38. c.failure = fmt.Sprintf("token rejected (status %s)", detail.Status)
  39. }
  40. return []byte{}, nil
  41. }