我一直在查看Oauth.Net Google Api,以便通过OAuth进行身份验证并使用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);
.

然后,您可以将凭据传递给服务的初始化程序。

通过上面进行, googleauthorizationcodeflow 将基于刷新令牌和客户机密的新访问令牌。

请注意,您必须在此处拥有客户端秘密,没有那个,您将无法获得访问令牌。

其他提示

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

我认为这篇文章将更好地解释您如何访问Google Apps API的OAuth 2.0,特别是如果您正在构建Web应用程序。

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

如果您对编码示例有兴趣,则sackageOverflow中有一个: google+ api:如何使用refreeshtokens来避免每次我的应用启动时请求访问?

GoogleWebauthorizationBroker要求您将其发送到indataStore中的Inclextation,在这种情况下发送了filedataStore。FileDataStore将数据存储在%appdata%中。如果您想使用RefreshToken,您将保存某个地方,否则您需要创建自己的IdataStore iclimation。

实际数据存储的代码我很长时间才能在这里发布。 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;
     }
.

该教程附有一个示例项目。

使用刷新令牌:

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

这应该创建一个文件夹令牌。json和内部文件夹是另一个json文件,它有您的 refresh_token。

{
    "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,因为它会在以下情况下自动启动web浏览器 未找到令牌。我更喜欢通过访问代码获取刷新令牌的旧学校方式。这与使用Google非常相似 OAuthUtil.CreateOAuth2AuthorizationUrlOAuthUtil.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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top