我如何实现谷歌适合api在.net web应用程序与用户登录?



我只是想使用google fit api来检索登录用户的数据(测试两个帐户)。但是我不明白如何从用户那里获得授权码/访问令牌。

另一个可能相关的问题,列出使用范围的同意页面没有出现。

我试着用谷歌。身份验证库

UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets()
{
ClientId = " *** ",
ClientSecret = " *** "
}, new[] { FitnessService.Scope.FitnessActivityRead, FitnessService.Scope.FitnessActivityWrite, FitnessService.Scope.FitnessSleepRead, FitnessService.Scope.FitnessSleepWrite },
"user", CancellationToken.None);
FitnessService fitnessService = new FitnessService(new BaseClientService.Initializer()
{
ApplicationName = "Exrecise App",
HttpClientInitializer = credential
});
var resp = await fitnessService.Users.Sessions.List("me").ExecuteAsync();

但是它把我带到了这个错误,也许我在console.cloud

中输入了错误的输入然后,从outthplayground复制令牌并将其粘贴到httpclient

HttpClient http = new HttpClient();
var resp = await http.SendAsync(new HttpRequestMessage()
{
RequestUri = new UriBuilder("https://www.googleapis.com/fitness/v1/users/me/sessions").Uri,
Headers =
{
{ "Authorization","Bearer ya29.token" } 
},
Method = HttpMethod.Get
});

这实际上得到了我想要的结果,但是我想从用户登录中得到它。

问题:我可以不使用常规的google身份验证来实现这一点吗?还是必须使用前一种方法?

这是我添加谷歌认证

builder.Services.AddAuthentication().AddGoogle(options =>
{
IConfigurationSection auth = builder.Configuration.GetSection("Authentication:Google");
options.ClientId = auth["ClientId"];
options.ClientSecret = auth["ClientSecret"];
options.CallbackPath = "/Home";
options.AuthorizationEndpoint += "?prompt=consent";
});

我错过了什么吗?

问题似乎是您没有提供重定向uri (https://cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.ICodeReceiver)

在GoogleWebAuthorizationBroker.AuthorizeAsync。

你需要在Google App中添加一个重定向uri,并将其添加到coderreceiver字段。这是用户接受应用程序后将被重定向的地方。

你可以找到更多关于机器授权和OAuth2.0认证与谷歌在这里

最新更新