无法从Google OAuth2令牌端点获取访问令牌

时间:2014-12-12 19:47:43

标签: c# asp.net oauth oauth-2.0 google-oauth

我试图从Google的授权终端检索访问令牌,但我不断收到401: Unauthorized

我非常确定发送的所有值(授权码,客户端ID,客户端密码,重定向uri和授权类型)都是正确的。

我的代码如下:

using (HttpClient client = new HttpClient()) {
    IEnumerable<KeyValuePair<string,string>> data = new List<KeyValuePair<string,string>> 
    {
          new KeyValuePair<string,string>("code", "CODE_HERE"),
          new KeyValuePair<string,string>("client_id", "CLIENT_ID_HERE"),
          new KeyValuePair<string,string>("client_secret", "CLIENT_SECRET_HERE"),
          new KeyValuePair<string,string>("redirect_uri", "REDIRECT_URI_HERE"),
          new KeyValuePair<string,string>("grant_type", "authorization_code"),
    }

    HttpContent content = new FormUrlEncodedContent(data);

    /* I'm getting 401 Unauthorized */
    HttpResponseMessage response = await client.PostAsync("https://www.googleapis.com/oauth2/v3/token", content);
}

响应的JSON是:

{
    "error": "invalid_client",
    "error_description": "Unauthorized"
}

然而,我是复制&amp;从我的Google Developer控制面板上粘贴客户的ID和客户的秘密,所以他们没有任何错误。

任何帮助?

1 个答案:

答案 0 :(得分:0)

这对我有用。在此示例中,我使用RefreshToken获取AccessToken。

var client_id = ConfigurationManager.AppSettings.Get("GoogleClientId");
                var client_secret = ConfigurationManager.AppSettings.Get("GoogleSecret");
                var grant_type = "refresh_token";

                var url = "https://www.googleapis.com/oauth2/v4/token";

                IEnumerable<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string,string>("client_id", client_id),
                    new KeyValuePair<string,string>("client_secret", client_secret),
                    new KeyValuePair<string,string>("grant_type", grant_type),
                    new KeyValuePair<string,string>("refresh_token", refreshToken),
                };

                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                HttpContent contentPost = new FormUrlEncodedContent(data);

                HttpResponseMessage response = await client.PostAsync(url, contentPost);
                var result = response.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<GoogleAPIAuth>(result);

这是我的GoogleAPIAuth类。

public class GoogleAPIAuth
    {
        public string client_secret { get; set; }
        public string grant_type { get; set; }
        public string refresh_token { get; set; }
        public string client_id { get; set; }
        public string access_token { get; set; }
        public string expires_in { get; set; }
        public string token_type { get; set; }
    }