Skip to content

Instantly share code, notes, and snippets.

@clonekim
Created July 23, 2020 03:28
Show Gist options
  • Save clonekim/be44312584c09ec520dd76418870b72b to your computer and use it in GitHub Desktop.
Save clonekim/be44312584c09ec520dd76418870b72b to your computer and use it in GitHub Desktop.
OAuth2 by Clojure
(ns backend.google.oauth
(:require [cheshire.core :refer [parse-string generate-string]]
[mount.core :refer [defstate]]
[buddy.core.keys :as keys]
[buddy.core.dsa :as dsa]
[backend.config :refer [env]]
[org.httpkit.client :as http])
(:import org.apache.commons.codec.binary.Base64))
(def access_token (atom nil))
(defstate private-key :start (-> env
:google
:private_key
(keys/str->private-key)))
(defn unixtime-now
([]
(-> (java.util.Date.)
(.getTime)
(/ 1000)
(.longValue))))
(defn- enc-header []
(-> {:alg "RS256"
:typ "JWT"}
(generate-string)
(.getBytes "UTF-8")
(Base64/encodeBase64String)))
(defn- enc-claim []
(-> {:iss "worker@code-speech.iam.gserviceaccount.com"
:scope "https://www.googleapis.com/auth/cloud-platform"
:aud "https://www.googleapis.com/oauth2/v4/token"
:exp (+ 3600 (unixtime-now))
:iat (unixtime-now)}
(generate-string)
(.getBytes "UTF-8")
(Base64/encodeBase64URLSafeString)))
(defn sig []
(let [h (enc-header)
c (enc-claim)
s (-> (clojure.string/join "." [h c])
(dsa/sign {:key private-key :alg :rsassa-pkcs15+sha256})
(Base64/encodeBase64URLSafeString))]
(clojure.string/join "." [h c s])))
(defn access-token []
(reset! access_token
(-> @(http/post "https://www.googleapis.com/oauth2/v4/token"
{:form-params
{:grant_type "urn:ietf:params:oauth:grant-type:jwt-bearer"
:assertion (sig)}})
:body
(parse-string true)
:access_token)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment