加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 使用ASP.NET Core后端服务器验证Google访问令牌

发布时间:2020-12-16 03:50:08 所属栏目:asp.Net 来源:网络整理
导读:我在客户端上有Angular2,在服务器端有ASP.NET Core.我使用 JavaScriptServices(aspnetcore-spa模板). 对于身份验证,我使用 OpenIddict,然后按照示例 here. 现在我在Controller类方法的服务器端,我想验证id_token,因为这是在this方面建议的: Important: Do n
我在客户端上有Angular2,在服务器端有ASP.NET Core.我使用 JavaScriptServices(aspnetcore-spa模板).
对于身份验证,我使用 OpenIddict,然后按照示例 here.

现在我在Controller类方法的服务器端,我想验证id_token,因为这是在this方面建议的:

Important: Do not use the Google IDs returned by getId() or the user’s
profile information to communicate the currently signed in user to
your backend server. Instead,send ID tokens,which can be securely
validated on the server.

我还想通过ASP.NET核心身份在我的数据库中注册用户(保存电子邮件,个人资料…).

我想使用Google API client Library for .NET获取用户信息并存储refresh_token.几年前我设法用PHP做到了,但我无法用.NET来解决这个问题.
我下载了nuget软件包:Google.Apis,Google.Apis.OAuth2.v2,Google.Apis.Plus.v1.

我不确定我需要哪个nuget包,我应该使用哪个类,如何设置Google ServerKey以及如何从我从gapi.signin2 button获得的信息中获取用户信息.

简单来说:
如何使用Google .NET Client库验证.NET中的id_token?

解决方法

我找到了解决方案 here.它很旧,但它确实有效.

var googleInitializer = new BaseClientService.Initializer();
googleInitializer.ApiKey = this.config["Authentication:Google:ServerKey"];
Oauth2Service ser = new Oauth2Service(googleInitializer);
Oauth2Service.TokeninfoRequest req = ser.Tokeninfo();
req.AccessToken = request.AccessToken;  //access token received from Google SignIn button
Tokeninfo userinfo = await req.ExecuteAsync();

我没弄明白如何在服务器上获取显示名称和图片.但它可以在客户端完成:

onGoogleLoginSuccess(user: gapi.auth2.GoogleUser)
{
    console.log("basic profile",user.getBasicProfile());
}

如果有人知道更新的解决方案或如何在服务器上检索基本用户配置文件,请分享.

另外我可以使用Google,但要小心,因为Google帐户不是Google帐户.我没有帐户并收到错误:

Google.Apis.Requests.RequestError Not Found [404] Errors [
Message[Not Found] Location[ – ] Reason[notFound] Domain[global] ]

在代码中:

var plusService = new PlusService(googleInitializer);
Person me = await plusService.People.Get(userinfo.UserId).ExecuteAsync();

但是可以获取所有用户信息(图片,显示名称,名字,姓氏,生日……)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读