Skip to content

Instantly share code, notes, and snippets.

@benjamin-asdf
Last active May 11, 2022 06:54
Show Gist options
  • Save benjamin-asdf/ed35f92dad7f3e50ac7a253cb59704f9 to your computer and use it in GitHub Desktop.
Save benjamin-asdf/ed35f92dad7f3e50ac7a253cb59704f9 to your computer and use it in GitHub Desktop.
Ths is for requesting tokens for a google service
(ns
org.sg.google.token
(:require
[cheshire.core :as json]
[babashka.curl :as curl]
[buddy.core.keys :as keys]
[buddy.sign.jwt :as jwt]
[clojure.string :as str])
(:gen-class))
(set! *warn-on-reflection* true)
(defn load-creds
"Takes a path to a service account .json credentials file"
[secrets-json-path]
(-> secrets-json-path slurp (json/parse-string keyword)))
(defn
create-claim
[creds & [{:keys [sub scopes]}]]
(let [^java.time.Instant now (java.time.Instant/now)
claim (merge
{:iss (:client_email creds)
:scope (str/join " " scopes)
:aud "https://oauth2.googleapis.com/token"
:exp (+ (.getEpochSecond now) (* 60 60))
:iat (.getEpochSecond now)}
(when
sub
;; when using the Admin API, delegating access, :sub may be needed
{:sub sub}))]
(jwt/sign
claim
(keys/str->private-key
(:private_key creds))
{:alg :rs256})))
(defn request-token [creds opts]
(let [claim (create-claim creds opts)
resp (curl/post
"https://www.googleapis.com/oauth2/v4/token"
{:form-params
{:grant_type "urn:ietf:params:oauth:grant-type:jwt-bearer"
:assertion claim}
:as :json})]
(if (= 200 (-> resp :status))
(-> resp :body (json/decode keyword) :access_token)
resp)))
(defn
auth
[request token]
(->
request
(assoc-in [:headers "Authorization"] (str "Bearer " token))))
(defn -main [credentials-path & scopes]
(println
(request-token
(load-creds credentials-path)
{:scopes scopes})))
(comment
(request-token
(load-creds "/home/benj/tmp/alert-drive-creds.json")
{:scopes ["https://www.googleapis.com/auth/spreadsheets.readonly"]}))
#_
(:deps {babashka/babashka.curl {:mvn/version "0.1.2"}
cheshire/cheshire {:mvn/version "5.10.2"}
babashka/fs {:mvn/version "0.1.6"}
org.clojure/data.csv {:mvn/version "1.0.1"}
buddy/buddy-sign {:mvn/version "3.4.333"}
buddy/buddy-core {:mvn/version "1.10.413"}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment