Googleドライブアカウントでファイルとフォルダーを一覧表示できるデスクトップアプリケーションを作成しようとしています. 現時点では、私はそれを行うことができますが、1 つの問題があります。アプリケーションから Google ドライブ アカウントを開くたびに再ログインする必要があります。毎回の再認証を避けるために、ローカルに保存された AccessToken/Refresh トークンを使用することは可能ですか?
ここでは、承認を取得するために使用されるメソッドです。
private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" });
// Get the auth URL:
state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob");
UriBuilder builder = new UriBuilder(arg.RequestUserAuthorization(state));
NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query);
queryParameters.Set("access_type", "offline");
queryParameters.Set("approval_prompt", "force");
queryParameters.Set("user_id", email);
builder.Query = queryParameters.ToString();
//Dialog window wich returns authcode
GoogleWebBrowserAuthenticator a = new GooogleWebBrowserAuthenticator(builder.Uri.ToString());
a.ShowDialog();
//Request authorization from the user (by opening a browser window):
string authCode = a.authCode;
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
解決済み:
最初に Google ドライブ SDK からメソッドを呼び出すには、サービスのインスタンスが必要です。
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, GoogleDriveHelper.CLIENT_ID, GoogleDriveHelper.CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
Service = new DriveService(auth);
これらの CLIENT_ID と CLIENT_SECRET は、Google API コンソールでアプリケーションにサインアップした後に取得できます。
次に、次のような GetAuthorization ルーチンを定義する必要があります。
private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" });
state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob");
state.RefreshToken = AccountInfo.RefreshToken;
state.AccessToken = AccountInfo.AccessToken;
arg.RefreshToken(state);
return state;
}
Refresh トークンと Access トークン (少なくとも Refresh) が既にある場合に機能します。そのため、最初にいくつかのユーザー アカウントを承認する必要があります。
次に、その Service インスタンスを使用して sdk メソッドを呼び出すことができます。それが誰かを助けることを願っています。