C# 使用存储的凭据进行授权。用于.NET的Google驱动API

C# 使用存储的凭据进行授权。用于.NET的Google驱动API,c#,.net,oauth,google-drive-api,C#,.net,Oauth,Google Drive Api,我正在尝试创建桌面应用程序,它将允许列出谷歌驱动器帐户上的文件和文件夹。在这个月我能做到,但有一个问题。每次我想从我的应用程序中打开google drive帐户时,我都必须重新登录。是否可以使用存储在本地的AccessToken/刷新令牌以避免每次重新授权 这里是用于获取授权的方法 private IAuthorizationState GetAuthorization(NativeApplicationClient arg) { IAuthorizationState

我正在尝试创建桌面应用程序,它将允许列出谷歌驱动器帐户上的文件和文件夹。在这个月我能做到,但有一个问题。每次我想从我的应用程序中打开google drive帐户时,我都必须重新登录。是否可以使用存储在本地的AccessToken/刷新令牌以避免每次重新授权

这里是用于获取授权的方法

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);
如果您已经拥有刷新和访问令牌(至少是刷新),那么它将起作用。因此,您需要先为某个用户帐户进行授权

然后可以使用该服务实例调用sdk方法。
希望它能帮助别人。

如何?你能和我分享吗。。。请告诉我您是否会遇到问题。您使用了哪个.net客户端来实现此目的?它仍然有效吗?
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;
    }