海雅都!我有以下代碼來設定我的 Google API:
// Open the FileStream to the related file.
using FileStream stream = new("Credentials.json", FileMode.Open, FileAccess.Read);
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
new[] { SheetsService.Scope.Spreadsheets, YouTubeService.Scope.YoutubeReadonly },
"admin",
CancellationToken.None,
new FileDataStore("Token", true),
new PromptCodeReceiver()
);
// Create Google Sheets API service.
builder.Services.AddSingleton(new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = name,
}));
// Create Youtube API service.
builder.Services.AddSingleton(new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = name,
}));
使用此代碼,我所有的服務都正確注入到我正在使用的服務提供者中。但是,在 ASP.Net 網站上線 7 天后似乎沒有重繪 令牌,即使我的令牌檔案有一個重繪 令牌。正如我想象的那樣,這是因為 OAuth 令牌僅持續 7 天。
那么,我如何讓 Google 的 API 自動重繪 我的令牌?由于這是一個網站,它需要長時間在線而不會因令牌過期而停機。
uj5u.com熱心網友回復:
如果您的應用仍在測驗中,重繪 令牌會在 7 天后過期。為了讓它們過期更長時間,您需要將您的應用程式設定為生產,并可能對其進行驗證。

Web 應用程式與已安裝的應用程式
我很驚訝您的代碼可以托管在網站上。GoogleWebAuthorizationBroker.AuthorizeAsync 適用于已安裝的應用程式。它不適用于托管在網站上的 Asp .net。它不起作用的原因是它導致同意瀏覽器在運行代碼的機器上打開。這將在開發中起作用,但是一旦您嘗試將它托管在網路服務器上,它就無法作業,因為服務器無法生成本地網路瀏覽器。
您應該關注Web 應用程式 (ASP.NET Core 3)
哪個將使用依賴注入
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};
});
}
您無需擔心重繪 您的訪問令牌,圖書館將為您處理。
uj5u.com熱心網友回復:
讓 ASP.NET 應用程式訪問 Youtube 和 Sheets 的想法是...
- 代表最終用戶或
- 代表自己(沒有最終用戶參與?
在 (1) 的情況下,使用GoogleWebAuthorizationBroker啟動 OAuth 授權流程是正確的方法,但您可能不應該永久存盤重繪 令牌。要么僅在最終用戶會話期間存盤它,要么根本不存盤它并在每次訪問令牌到期時觸發新的 OAuth 授權流。
在 (2) 的情況下,您應該使用服務帳戶并使用 加載憑據GoogleCredentials.GetApplicationDefaultAsync()。如果應用在 GCP 上運行,則將服務帳號附加到底層計算資源;如果它在其他地方運行,您可以使用 Workload 聯合身份驗證或服務帳戶密鑰。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370975.html
標籤:网站 谷歌API 谷歌oauth youtube-data-api google-api-dotnet-client
上一篇:UPDATE查詢更新所有資料
