oauth-2.0 - 如何在 ASP.NET Core MVC OAuth 2.0 中获取访问 token 的值

标签 oauth-2.0 asp.net-core-mvc google-oauth

在 Visual Studio 2017RC 中,我使用个人用户帐户创建了 ASP.NET Core MVC 应用程序并成功完成 https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins附加 Google 身份验证的教程。我现在已通过我的 Google 帐户登录。

我所做的就是向自动生成的代码添加几行(在 Startup.cs 的配置方法中):

app.UseGoogleAuthentication(new GoogleOptions
{
    ClientId = "xxxx.apps.googleusercontent.com",
    ClientSecret = "xxxx",
    Scope = { "email", "openid" }
});

我现在需要获取由 Google 颁发的访问 token 的值(并由应用程序存储在 cookie 中)。然后我将使用它生成 XOAuth2 key 以访问 Google 服务。例如,在 HomeController 的 About 方法(由标准向导自动生成)中,我想显示收件箱中未读电子邮件的数量。使用 XOAuth2 key ,我可以登录 Gmail 并从这里继续。

我怎样才能得到这个 token ? - 在通过 Google 初始登录期间,我是否需要将访问 token 存储在数据库中?如果是这样,有什么线索可以在标准向导生成的 ASP.NET Core MVC 应用程序中完成此操作吗? - 或者,也许我总是可以从 cookie 中读取访问 token ?如果是这样,怎么办?

最好,我从 cookies 中读取它(它无论如何都在那里),并避免在数据库中复制此信息,但不确定这种方法是否可行(即是否可以解密)。

我曾经为 ASP.NET MVC 做过一次,但在 ASP.NET Core MVC 中事情发生了很大变化,遗留代码不再有用。

最佳答案

好的,找到了。 SaveTokens 属性可以解决这个问题。

app.UseGoogleAuthentication(new GoogleOptions
{
    ClientId = "xxxx.apps.googleusercontent.com",
    ClientSecret = "xxxx",
    Scope = { "email", "openid" },
    SaveTokens = true,
    AccessType = "offline"
});

然后我可以在 AccountController.ExternalLoginCallback 中获取访问 token

var token = info.AuthenticationTokens.Single(x => x.Name == "access_token").Value;

关于oauth-2.0 - 如何在 ASP.NET Core MVC OAuth 2.0 中获取访问 token 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524213/

相关文章:

oauth-2.0 - KeyCloak用户角色: reset password endpoint for own account only

asp.net-core - .NET Core MVC 页面更改后不刷新

c# - .net 谷歌日历 API : anybody can create/update/delete events

oauth-2.0 - 如何使用 OAuth 告诉 Grafana 某个用户是管理员或属于某个组织?

authentication - 如何刷新 token 而无需再次进行身份验证? OAuth2

oauth-2.0 - OpenID Connect - 如何处理单次注销

c# - MVC6 强类型操作链接和 View

c# - 在 Tag helper .net core 中设置默认值

google-oauth - 支持 Form Post 响应模式吗?

python - "Insufficient Permission: Request had insufficient authentication scopes"即使是最通用的范围