XOAuth provides a Go implementation of two-legged oauth for logging into Gmail via IMAP using its XOAUTH protocol support.
Although OAuth 1.x has been officially deprecated by Google, it remains the only way to build apps that allow for domain-wide delegation of authority.
As Google states:
Using 2-legged OAuth allows for domain-wide delegation of authority. A domain administrator can authorize access requests for all users. An application that has the OAuth consumer key and secret (roughly equivalent to a role account username and password) is allowed to act as any user in the domain when accessing Google Data APIs.
This implementation is based on a Javascript implementation which is in turn derived from Google's Python implementation.
It can be used for regular OAuth client access if you already have tokens, but it has only been tested with the domain-wide consumer key and secret.
Use the go tool to install XOAuth:
go get github.com/agamz/xoauth
Docs are here: http://godoc.org/github.com/agamz/xoauth.
To generate a valid string for use with the Gmail XOAUTH login, you will need:
- the email address you're going to access. This must be in a (Google Apps) domain that you have access to, or login will fail.
- the consumer key provided to you by Google
- the consumer secret provided to you by Google
Generate the string as follows:
include "github.com/agamz/xoauth"
...
User := "some.person@example.com"
ConsumerKey = "magic key"
ConsumerSecret = "magic key secret"
xoauthstring := xoauth.GenerateXOauthString(ConsumerKey, ConsumerSecret, "", "", User, "imap", User, "", "")
You can then pass this to your favourite Gmail IMAP library as needed. For example, you can use the excellent go-imap library. For that library, you'll need to provide an XOAUTH SASL implementation:
type xoAuth []byte
func XoAuth(identity string) imap.SASL {
return xoAuth(identity)
}
func (a xoAuth) Start(s *imap.ServerInfo) (mech string, ir []byte, err error) {
return "XOAUTH", a, nil
}
func (a xoAuth) Next(challenge []byte) (response []byte, err error) {
return nil, errors.New("unexpected server challenge")
}
Now you can call its Auth
function to login:
include "code.google.com/p/go-imap/go1/imap"
func callimap() {
var c *imap.Client
....
xoauthstring := xoauth.GenerateXOauthString(ConsumerKey, ConsumerSecret, "", "", User, "imap", User, "", "")
c.Auth(XoAuth(xoauthstring)))
....
}
Contributions are welcome! More examples or source code changes are both solicited.
Please be sure that go test
works before submitting pull requests.
##License
XOAuth is available under the BSD License.