.NET Google API 1.7 ベータ版のリフレッシュ トークンによる認証
-
21-12-2019 - |
質問
OAuth 経由で認証し、Google ドライブ API を使用するために、Oauth .Net Google API を調べてきました。
具体的には、GoogleDrive サービスのインスタンス化に使用するために、すでに保存しているリフレッシュ トークンを使用したいと考えています。
のようなサンプルを見つけましたhttps://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples
これは「GoogleWebAuthorizationBroker.AuthorizeAsync」を使用しているようですが、この例で供給しているように見えるクライアントシークレットではなく、リフレッシュトークンでそのメソッドをどのように使用できるかわかりません。
解決
私が正しく理解しているなら、あなたは既存のリフレッシュトークンに基づいて新しいGoogleサービスをどのように作成することができるかを尋ねています。
だから、次のことができます。
var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = [your_client_secrets_here]
}), "user", token);
.
その後、資格情報をサービスのイニシャライザに渡すことができます。
上記をすることで、 googleAthorizationCodeflow は、最新のトークンとクライアントの秘密を更新した新しいアクセストークンを取得します。
ここでは、ここでクライアント秘密が必要な場合は、アクセストークンを取得できません。
他のヒント
client_secrets.jsonには、クライアントIDとクライアントの秘密(アプリケーションのためのOAuth 2.0の情報があります)が含まれています。
この記事では、Webアプリケーションを構築している場合は、Google Apps APIにアクセスするには、Google Apps APIにアクセスする方法をさらに詳しく説明します。
https://developers.google.com/accounts/docs/oauth2webserver
コーディング例に興味がある場合は、stackoverflowに1つあります。 Google+ API:私のアプリが起動するたびにアクセスを要求するのを避けるためにリフレッシュトークンを使うことができますか?
GoogleWebAuthorizationBrokerは、この場合はFileDataStoreが送信されたIDatastoreの紹介を送信する必要があります。FileDataStoreは、%AppData%にデータを格納します。あなたが更新されたわたしの更新されたテクノロジを使いたいのなら、他の場所であなたはあなた自身のIdatastoreの推論を作成する必要があります。
実際のデータストアのコードここで投稿するのは少し長いです。>> http://aimto.com/google-oauth2-csharp/
あなたはそれをあなたがFileDataStore
と同じようにそれを使う//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile },
"user",
CancellationToken.None,
new SavedDataStore(myStoredResponse)).Result;
}
.
そのチュートリアルに添付されたサンプルプロジェクトがあります。
リフレッシュトークンを使用するには:
var init = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "OAuth_Client_ID_From_GoogleAPI",
ClientSecret = "OAuth_Client_Secret"
},
Scopes = new string[] {"MY_SCOPES"}
};
var token = new TokenResponse { RefreshToken = "MY_REFRESH_TOKEN" };
var credential = new UserCredential(new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(init), "", token);
//init your Google API service, in this example Google Directory
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "",
});
リフレッシュ トークンがない場合はどうすればよいでしょうか?最も簡単なのは、Google SDK ドキュメントの指示に従うことです。最初にGoogle APIプロジェクトから資格情報をダウンロードします。ファイルに名前を付けます credentials.json
. 。次に、コードを実行します。
using (var stream =
new FileStream("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.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
これにより、フォルダーtoken.jsonと内側のフォルダーが作成されるはずです。refresh_tokenがある別のJSONファイルです。
{
"access_token" : "asdf",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "XXX",
"scope" : "https://www.googleapis.com/auth/admin.directory.user.readonly",
"Issued" : "2019-02-08T12:37:06.157-08:00",
"IssuedUtc" : "2019-02-08T20:37:06.157Z"
}
トークンが見つからないときにWebブラウザーを自動化するため、GoogleWeBauthorizationBrokerを使用しないことを好みます。私は、アクセス コードによってリフレッシュ トークンを取得する昔ながらの方法を好みます。これは、Google を使用するのと非常によく似ています。 OAuthUtil.CreateOAuth2AuthorizationUrl
そして OAuthUtil.GetAccessToken
Google の従来の OAuth API で。
var a = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "asdf",
ClientSecret = "hij"
},
Scopes = Scopes
};
var flow = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(a);
var url = flow.CreateAuthorizationCodeRequest(GoogleAuthConsts.InstalledAppRedirectUri).Build().AbsoluteUri;
Console.WriteLine("Go to this URL and get access code: " + url);
Console.Write("Enter access code: ");
var code = Console.ReadLine();
Console.WriteLine("Fetching token for code: _" + code + "_");
var r = flow.ExchangeCodeForTokenAsync("user", code, GoogleAuthConsts.InstalledAppRedirectUri, CancellationToken.None).Result;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(r));