oauth-two icon indicating copy to clipboard operation
oauth-two copied to clipboard

OAuth 2.0 client in Clojure

#+TITLE: OAuth Two #+STARTUP: overview

#+BEGIN_HTML #+END_HTML

  • Installation This project is under active development, and has yet to reach 1.0. As such the API may change.

#+BEGIN_HTML #+END_HTML

  • Getting started Require the library with a convenient alias that we can make use of later.

#+begin_src clojure (require '[oauth.two :as two]) #+end_src

Create a client using the credentials provided by (in this example) Vimeo. The client holds on to important URLs, and tokens. We'll pull our client ID and secret from environment variablesa to avoid adding sensitive credentials to our repository.

#+begin_src clojure (def client (two/make-client {:access-uri "https://api.vimeo.com/oauth/access_token" :authorize-uri "https://api.vimeo.com/oauth/authorize" :id (System/getenv "VIMEO_CLIENT_ID") :secret (System/getenv "VIMEO_CLIENT_SECRET")})) #+end_src

The ~:access-uri~ is where we get access tokens, and the :authorize-uri is where we redirect users to show them the provider's site.

** Generate provider-specific redirect URL To kick off the OAuth dance we need to create a URL to send the user to. This URL is owned by the OAuth provider, and it's where the provider asks the user if they want to grant us access.

To generate the authorisation URL we use the ~authorization-url~ function like so:

#+begin_src clojure (two/authorization-url client) #+end_src

We can pass in additional parameters to include in the OAuth authorisation URL by providing an optional map as the second argument.

#+begin_src clojure (two/authorization-url client {:state "hello world"}) #+end_src

A third optional argument allows you to pass additional query parameters, like [[https://developers.google.com/identity/protocols/OAuth2WebServer][Google's "prompt" parameter]].

#+begin_src clojure (two/authorization-url client {:state "hello world"} {:prompt "select_account"}) #+end_src

** Handle response from provider When the user decides to accept our request to access his or her account we receive a ~GET~ request by virtue of the provider redirecting the user to us.

Query parameters are appended to our ~:callback-uri~ that inform us if the authorisation request was successful or not.

*** Success This redirect includes an authorisation code, and any local state provided previously.

| Field | Required | Description | |---------+----------+--------------------------------------------| | ~code~ | REQUIRED | The auth code generated by the Auth server | | ~state~ | REQUIRED | Whatever value we passed previously |

#+begin_quote The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. #+end_quote

*** Failure If something goes wrong the Auth server redirects back to the client with the following parameters:

| Field | Required | Description | |---------------------+----------+-------------------------------------------| | ~error~ | REQUIRED | A single ASCII error code | | ~error_description~ | OPTIONAL | Human-readable ASCII error description | | ~error_uri~ | OPTIONAL | A URI with more human-readable error info | | ~state~ | REQUIRED | Whatever value we passed previously |

Error codes are as follows:

| Error | Description | |-----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ~unauthorized_client~ | The client is not authorized to request an authorization code using this method. | | ~access_denied~ | The resource owner or authorization server denied the request. | | ~unsupported_response_type~ | The authorization server does not support obtaining an authorization code using this method. | | ~invalid_scope~ | The requested scope is invalid, unknown, or malformed. | | ~server_error~ | The authorization server encountered an unexpected condition that prevented it from fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status code cannot be returned to the client via an HTTP redirect.) | | ~temporarily_unavailable~ | The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. (This error code is needed because a 503 Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.) |

#+begin_src http HTTP/1.1 302 Found Location: https://client.example.com/cb?error=access_denied&state=xyz #+end_src

** Request access token With the ~code~ from the provider we can generate a request map for getting our access token via the ~access-token-request~.

#+begin_src clojure (two/access-token-request (make-client {:access-uri "http://example.com/oauth/access-token" :id "id" :secret "secret"}) {:code "abc"}) #+end_src

This will produce a request map with ~Basic~ authentication via the client's ID and secret in addition to the ~code~.

#+begin_src clojure {:request-method :post, :url "http://example.com/oauth/access-token", :headers {"authorization" "Basic aWQ6c2VjcmV0", "content-type" "application/x-www-form-urlencoded"}, :body "client_id=id&code=abc&grant_type=authorization_code"} #+end_src

You can then issue this request using your favourite HTTP client, with any error handling, JSON response parsing, metrics etc.

All OAuth 2.0 providers will return a custom response to the access token request. The spec provides the following JSON as an example response:

#+begin_src json { "access_token": "2YotnFZFEjr1zCsicMWpAA", "token_type": "example", "expires_in": 3600, "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter": "example_value" } #+end_src

https://tools.ietf.org/html/rfc6749#section-4.1.4

The spec goes on to define how these attributes should be used in other flows.

#+begin_example access_token REQUIRED. The access token issued by the authorization server.

token_type REQUIRED. The type of the token issued as described in Section 7.1. Value is case insensitive.

expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value.

scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token as described by Section 3.3.

state REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. #+end_example