Created
March 29, 2024 14:30
-
-
Save JohnnyJayJay/6c21379afb2f2de05303b2c39bac3dd6 to your computer and use it in GitHub Desktop.
babashka script to quickly perform the oauth2 authorization_code flow locally to get an access token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bb | |
(require | |
'[babashka.http-client :as hc] | |
'[babashka.deps :as deps] | |
'[org.httpkit.server :as hs] | |
'[clojure.java.browse :refer [browse-url]]) | |
(deps/add-deps '{:deps {ring/ring-core {:mvn/version "1.12.1"}}}) | |
(println "Reading oauth2 params from STDIN") | |
(def oauth-params (read)) | |
(defn handler [{{:keys [code]} :params :keys [uri]}] | |
(if (= uri "/") | |
{:status 302 | |
:headers {"location" | |
(str (:authorize-uri oauth-params) | |
"?response_type=code" | |
"&client_id=" (:client-id oauth-params) | |
"&redirect_uri=" (java.net.URLEncoder/encode "http://localhost:8080/callback") | |
"&scope=" (java.net.URLEncoder/encode (:scope oauth-params)) | |
"&state=abcdef")}} | |
{:status 200 | |
:headers {"content-type" "application/json"} | |
:body (:body | |
(hc/post | |
(:access-token-uri oauth-params) | |
{:form-params {:code code | |
:grant_type "authorization_code" | |
:client_id (:client-id oauth-params) | |
:redirect_uri "http://localhost:8080/callback"} | |
:basic-auth [(:client-id oauth-params) (:client-secret oauth-params)]}))})) | |
(require '[ring.middleware.params :refer [wrap-params]] | |
'[ring.middleware.keyword-params :refer [wrap-keyword-params]]) | |
(println "starting HTTP server") | |
(def stop-server (hs/run-server (-> handler wrap-keyword-params wrap-params) {:port 8080})) | |
(browse-url "http://localhost:8080") | |
(while true (Thread/sleep 1000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment