Using OAuth2 with Emacs

I've been playing with the GitHub API, through Emacs. For all the interesting stuff, it needs OAuth2 authorization, and though there's good support in Emacs for OAuth2, I couldn't find a getting started guide. So, here goes:

First you'll need an access token. The standard way of getting an access token - redirect to the service (Github), authorize, redirect back to your website - isn't going to help us much. We don't have a website to come back to. It's just an Emacs client. But there's an alternative, and all the providers I've played around with so far support it. They'll issue you an access token manually for personal use.

So, we head off to Github > Account Settings > Applications and there's a box marked "Personal Access Tokens". Creating one of those gives us a token like 8914803c3f5038531dec13166ce098710c649281.

With that magic string we're away. Require the package (you may need to M-x package-install it first), then create an oauth2-token struct:

(require 'oauth2)
(defvar my-token
  (make-oauth2-token :access-token "8914803c3f5038531dec13166ce098710c649281"))

With that we turn to oauth2-url-retrieve-synchronously. It will take a token and a url and return a buffer containing the HTTP response. We can dip into that buffer and read the JSON like this:

(require 'json)
(defvar user-data
  (with-current-buffer
      (oauth2-url-retrieve-synchronously my-token "https://api.github.com/user")
    (goto-char url-http-end-of-headers)
    (json-read)))

Job done. Let's just pull out an item:

(cdr (assoc 'name user-data))
Kris Jenkins

And that's all there is to it. (Or at least, enough to get you started...)