Google OAuth2使用.net从刷新令牌获取访问令牌

时间:2019-05-05 21:54:23

标签: c# .net oauth-2.0 google-api access-token

我想从刷新令牌中获取访问令牌以在服务器中发送电子邮件 但是我收到 400“ Bad Request” 错误。 这是我在客户端

上使用的代码
      var CLIENT_ID = 'A';
      var CLIENT_SECRET = 'B';

      var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
      var SCOPES = 'https://mail.google.com/';

function initClient() {
    gapi.client.init({
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
    }).then(function() {
        gapi.auth2.getAuthInstance().grantOfflineAccess().then(offline);
    }, function(error) {

    });
}

function offline(rtn) {
    var refreshToken = rtn.code;

}

这是我在服务器端上使用的c#.net代码以获取访问令牌

var secrets = new ClientSecrets
            {
                ClientId = "A",
                ClientSecret = "B"
            };


            HttpClient xclient = new HttpClient();
            xclient.BaseAddress = new Uri("https://www.googleapis.com");

            var refreshMessage = new HttpRequestMessage(HttpMethod.Post, "/oauth2/v4/token")
            {
                Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>("client_id", secrets.ClientId),
                new KeyValuePair<string, string>("client_secret", secrets.ClientSecret),
                new KeyValuePair<string, string>("refresh_token", refreshToken),
                new KeyValuePair<string, string>("grant_type", "refresh_token")
            })
            };


            Task.Run(async () =>
            {
                var response = await xclient.SendAsync(refreshMessage);
                if (response.IsSuccessStatusCode)
                {
                    var tokenResponse = await response.Content.ReadAsStringAsync();


                }
            }).GetAwaiter().GetResult();

怎么了?

0 个答案:

没有答案