gpt4 book ai didi

asp.net-mvc - MVC 应用程序中的 Google OAuth 访问 token 过期?

转载 作者:行者123 更新时间:2023-12-02 03:45:10 25 4
gpt4 key购买 nike

我按照此处的说明使用 Google Oauth2 编写了一个 MVC 应用程序: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web_applications

我遇到访问 token 过期问题。当访问 token 过期时,我在调用 Google API 时遇到异常:“访问 token 已过期,但我们无法刷新它”

初始认证是两次迭代机制:

第一次迭代 AuthorizeAsync 返回带有空 Credential 的结果,并填充 RedirectUri:

因此,创建的授权网址是这样的:

https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=MYCLIENTID&redirect_uri=http:%2F%2Flocalhost%2FHomepage%2FAuthCallback%2FIndexAsync&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar https:%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&state=http:%2F%2Flocalhost%2FHomepage%2F95419199

请注意存在 access_type=offline。所以我也应该取回刷新 token (没有发生)。

enter image description here

第二次迭代 - AuthorizeAsync 返回带有填充的凭据和空 RedirectUri 的结果:

问题1 - RefreshToken 此时是否应该为 null?

enter image description here

结果会被记住,因为它被定义为静态。

传入的下一个请求 - 需要结果的日历操作。调用 Google Calendar API 的凭据:

问题2 - 如果访问 token 在那一刻过期(为了测试,我只是设置 ExpiresInSeconds = 0),我调用 RefreshTokenAsync 方法,但它总是返回 false!为什么?我在这里缺少什么?

当 RefreshTokenAsync 返回 false 时,正确的处理方法是什么?当前 RedirectResult(result.RedirectUri) 命令将失败,因为 result.RedirectUri 为 null。

enter image description here

最佳答案

哦,我终于明白了:)对于那些感兴趣的人 - 刷新 token 仅发出一次,当您看到“同意”屏幕时,您必须单击"is"。

因此,为了获取刷新 token ,请转到您的帐户设置,帐户权限:https://security.google.com/settings/security/permissions

并撤销您在 Google Developers Console 中配置的项目的访问权限:https://console.developers.google.com/project

现在,在调用 AuthorizeAsync 后在下一行放置一个断点,在 Debug模式下重新启动应用程序,获取请求权限的同意屏幕,然后单击“接受”。

应用程序将返回到 VS 并在您的断点处停止。

现在,在某处记录 result.Credential.Token.RefreshToken 值,它是一个加密字符串。

为了简单起见,我将其放在 web.config 应用程序设置中。

现在,我只需将该值分配回 result.Credential.Token.RefreshToken = refreshToken;

并且每次当访问 token 过期时,它都会自动刷新。

enter image description here

就像这里,当我调用 GmailService request.Execute(...) 并传递包含 token 的凭据对象时, token 将被刷新。

enter image description here

关于asp.net-mvc - MVC 应用程序中的 Google OAuth 访问 token 过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678496/

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