4

我正在尝试创建桌面应用程序,它允许列出谷歌驱动器帐户上的文件和文件夹。在这一刻,我可以做到,但有一个问题。每次我想从我的应用程序中打开 google drive 帐户时,我都必须重新登录。是否可以使用本地存储的 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 Drive 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 方法。希望它会帮助某人。

4

0 回答 0