gpt4 book ai didi

clojure - 在compojure中实现oauth2,如何在响应用户请求之前等待第二个oauth2回调?

转载 作者:行者123 更新时间:2023-12-02 11:09:01 25 4
gpt4 key购买 nike

我想让 OpenID 连接在我的小 luminus 项目中工作。我对 luminus/ring/compojure 中的工作流程有点陌生(主要来自 django、flask 和 servlet)。我已成功重定向到 Google,因此我从 Google 获取了“代码”,但随后我需要在登录用户之前向 Google 再次发出请求,并且此调用需要用户未参与的另一次回调,因此我需要像 promise 一样搁置用户的请求,但我不确定该部分在 compojure 中如何工作。

; this is my code that redirects them to Google, where they accept
(defn login [params]
(let [google-oauth2-client-id (System/getenv "GOOGLE_OAUTH2_CLIENT_ID")
base-url "https://accounts.google.com/o/oauth2/auth"
args {"client_id" google-oauth2-client-id
"response_type" "code"
"scope" "openid email"
"redirect_uri" "http://localhost:3000/oauth2Callback"
"state" "anti-forgery here"}]

(assert google-oauth2-client-id "can't find GOOGLE_OAUTH2_CLIENT_ID in environment")

(redirect (str base-url "?" (make-query-string args)))
)
)

; this is my code handling Google's first response
(defn oauth2-callback [params]
; params has the code to send to Google

; here I should send another request to google that comes back to another callback like oauth2-token-callback that processes the request to the user in the current context

(redirect "/youreloggedin")
)

在此方法结束时,我应该向用户发送一条消息,表明他们已登录,但我需要等到请求返回。这个工作流程在 luminus 中是如何处理的?

<小时/>

已解决。我没有意识到我可以忽略回调参数。

  (client/post "https://www.googleapis.com/oauth2/v3/token"
{:headers {"X-Api-Version" "2"}
:content-type :application/x-www-form-urlencoded
:form-params {:code (params :code)
:client_id (System/getenv "GOOGLE_OAUTH2_CLIENT_ID")
:client_secret (System/getenv "GOOGLE_OAUTH2_CLIENT_SECRET")
:redirect_uri "http://localhost:3000/oauth2Callback" ; ignored
:grant_type "authorization_code"
}
:as :auto ; decode the body straight to hash (if possible)
})

最佳答案

基于适用于网络服务器的 Google OAuth2 文档 here ,流程由以下步骤组成:

  1. 您的应用程序将浏览器重定向到 Google 网址; URL 包含指示所请求的访问类型的查询参数。
  2. 结果是一个授权代码,Google 将其通过查询字符串返回到您的应用程序。
  3. 收到授权代码后,您的应用可以用该代码(以及客户端 ID 和客户端 key )交换访问 token ,在某些情况下还可以交换刷新 token 。

如果我正确理解您的问题,第 3 步不一定涉及对您的服务器的回调,您只需使用 HTTP 客户端向 Google 执行请求即可。我最近在这个 project 中为 GitHub 实现了 OAuth2 ,步骤3是在这个function中实现的:

(defn callback
"Handles the callback from GitHub OAuth flow."
[code]
(let [params {:form-params {:client_id client-id
:client_secret client-secret
:code code}}
{:keys [body]} (client/post access-token-url params) ;; This is doing the POST
;; request to GitHub.
token ((qs-map body) "access_token")] ;; Getting the token from
;; the response here.
{:status 302
:headers {"location" "/repos"
"set-cookie" (str "token=" token ";Path=/")}}))

我用了clj-http作为 HTTP 客户端,但任何其他客户端都可以。

关于clojure - 在compojure中实现oauth2,如何在响应用户请求之前等待第二个oauth2回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com