与刷新令牌.NET API谷歌测试版1.7认证

问题描述 投票:7回答:4

我为了通过OAuth认证,并使用谷歌驱动蜜蜂一直在看的Oauth净谷歌的API。

具体而言,我想用一个刷新令牌我已经存储起来,以便用它来实例化一个Google云端硬盘服务。

我发现像https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples样本

这似乎用“GoogleWebAuthorizationBroker.AuthorizeAsync”,但我不知道怎么用这个方法有刷新令牌,而不是你似乎在这个例子中可以喂养它的客户端机密。

c# google-drive-sdk google-oauth google-api-dotnet-client
4个回答
16
投票

如果我理解正确的话,你是问你怎么能创建一个新的谷歌服务,基于现有的刷新令牌。

所以,你可以做到以下几点:

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);

然后,你可以通过你的凭据服务的初始化。

通过这样做上面的,你刷新令牌和客户端秘密GoogleAuthorizationCodeFlow将获得基于新的访问令牌。

请注意,您必须拥有客户端秘密在这里,没有这一点,你将无法获得访问令牌。


0
投票

该client_secrets.json中包含客户端ID和客户端密钥(其中有您的OAuth 2.0信息您的应用程序)。

我想,这篇文章将更好地解释了如何的OAuth 2.0尤其是谷歌访问企业应用套件API,如果你正在建设一个Web应用程序。

https://developers.google.com/accounts/docs/OAuth2WebServer

如果你有兴趣在编码例子,有一个在计算器:Google+ API: How can I use RefreshTokens to avoid requesting access every time my app launches?


0
投票

GoogleWebAuthorizationBroker要求您发送iDataStore的implimtation在这种情况下FileDatastore发送。 FileDataStore存储在%APPDATA%的数据。如果你想使用一个refreshtoken你到别的什么地方保存,你需要创建自己的iDataStore的implimitation。

对于实际数据存储我有点长的代码张贴在这里。 http://daimto.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;
     }

有连接到该教程的示例项目。


0
投票

要使用刷新令牌:

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 = "",
});

如果你没有什么刷新令牌?最简单的是遵循谷歌SDK文档的说明。首先下载谷歌从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"
}

我喜欢,因为当找不到令牌就自动启动一个网页浏览器不使用GoogleWebAuthorizationBroker。我更喜欢通过接入码获取刷新令牌的老同学的方式。这是非常相似的使用谷歌OAuthUtil.CreateOAuth2AuthorizationUrlOAuthUtil.GetAccessToken在谷歌的传统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));
© www.soinside.com 2019 - 2024. All rights reserved.