刷新从 Google Identity Services / React App 收到的访问令牌

Pet*_*rov 2 access-token jwt reactjs google-identity refresh-token

我现在在处理从 Google Identity Services 收到的访问令牌时遇到了麻烦。

有关此案的一些细节。我有全栈应用程序,后端基于Spring/Webflux/Hibernate-Reactive,前端基于React。我正在使用 Google Identity Services 的 google 登录功能以及此反应库@react-oauth/google

我正在使用成功登录后收到的“凭据”进行后端访问。一切都按预期工作,只是成功登录后响应中没有刷新令牌。令牌在 1 小时后过期,必须提示用户重新登录才能收到新令牌,这太可怕了!

那么,如何刷新这个令牌,有什么想法吗?

我在谷歌方面找不到更多信息,这就是我在这里写下的原因。

Pet*_*rov 5

所以我自己找到了解决方案。我将其发布在这里,希望能帮助其他正在解决这个问题的人。

因此,使用react库@react-oauth/google我使用了useGoogleLogin钩子。我将“ flow: 'auth-code' ”添加到函数的选项对象中。

const login = useGoogleLogin({
    onSuccess: codeResponse => console.log(codeResponse),
    flow: 'auth-code',
});
Run Code Online (Sandbox Code Playgroud)

该功能通过单击简单的按钮来触发。

用户成功登录后,在响应对象中我们可以找到一个code属性。我们可以通过调用 google oauth2 api 来交换访问、刷新和 id 令牌的代码:

curl --location --request POST 'https://oauth2.googleapis.com/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=your_client_id' \
--data-urlencode 'client_secret=your_client_secret' \
--data-urlencode 'code=recieved_code_after_login' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'redirect_uri=one of your redirect uri's listed in your 
credential'
Run Code Online (Sandbox Code Playgroud)

请求访问成功后,收到刷新和id token。

刷新令牌也如此简单:

curl --location --request POST 'https://oauth2.googleapis.com/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=your_client_id' \
--data-urlencode 'client_secret=your_client_secret' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'refresh_token=received_refresh_token'
Run Code Online (Sandbox Code Playgroud)

这是原始的 Google 文档:https://developers.google.com/identity/protocols/oauth2/web-server#httprest_3

!重要的!请记住,在访问权限被撤销之前,刷新一直有效。当您刷新令牌时,响应中不会附带新的刷新令牌。如需进一步刷新,您可以使用通过交易所接收的相同刷新令牌。