Google API.NET客户端-如何获取C#ASP.NET Core Web API客户端的OAuth2访问令牌和刷



如何获取C#ASP.NET Core Web API客户端的OAuth2访问令牌和刷新令牌以验证YouTube Data API v3

在这种情况下,用户名没有用户界面可以手动输入用户名和密码,然后接收代码来获取令牌。不需要redirect_uri。

如何获取访问令牌和刷新令牌

我曾经用微软Azure AD解决了一个类似的问题,stackoverflow 的解决方案

我只是找不到任何关于这个场景的谷歌云平台.NET客户端的信息

自2015年以来,您不能将客户端登录(用户名和密码(与任何Google api一起使用。您需要使用Oauth2对用户进行身份验证。

您需要首先配置库。

public void ConfigureServices(IServiceCollection services)
{
...
// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = {YOUR_CLIENT_ID};
options.ClientSecret = {YOUR_CLIENT_SECRET};
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAuthentication();
app.UseAuthorization();
...
}

然后你可以对YouTube API进行任何你喜欢的调用。当达到此端点时,将提示用户同意授权。

[GoogleScopedAuthorize(YouTubeService.ScopeConstants.Readonly)]
public async Task<IActionResult> YouTubeCall([FromServices] IGoogleAuthProvider auth)
{
GoogleCredential cred = await auth.GetCredentialAsync();
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});

// your call to the youTube service here.
}

我建议你看看Asp.net核心的示例,但它在谷歌驱动器中,你需要修改它

客户端库应该为你提供所有的访问令牌和刷新令牌,但如果你真的想访问它们,这里有一些关于如何使用#1725的信息

最新更新