在Google oAuth C中交换访问令牌代码时获取错误400#

时间:2013-10-03 23:04:32

标签: google-api

  WebRequest request = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
    request.Method = "POST";
    string postData = "code=" + code + "&client_id=" + _clientId + "&client_secret=" + _clientSecret + "&redirect_uri=" + _callback_url + "&grant_type=authorization_code";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;

    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    WebResponse response = request.GetResponse();

我在HTML页面中放置了一个google登录按钮,在其回调中获得了auth代码来调用包含上述代码的ajax web服务。但我在GetResponse()上得到错误400,我不知道为什么。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我发现在我的案例中可以使用以下链接:

页面上的代码页面加载:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request["code"] != null)
    {
        vCode = Request["code"].ToString();
        getRefreshToken();
    }
    else
    {
        Response.Redirect(vAuthURL + "?scope=" + vScope + "&state=%2Fprofile&client_id=" + vClientId + "&redirect_uri=" + vRedURL + "&response_type=code&access_type=offline&approval_prompt=force", false);
    }
}

当代码可用时,在页面加载中调用以下函数:

private void getRefreshToken()
{
string vClientId = "974762xxxxxx-xxxxxxxxx.apps.googleusercontent.com";
string vSecCode = "xxxxxxxxxxxxxxx";
string vScope = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login";
string vRedURL = "http://localhost:50488/wwwroot/member/social/googlesignin.aspx";
string vAuthURL = "https://accounts.google.com/o/oauth2/auth";

 StringBuilder authLink = new StringBuilder();
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.Method = "POST";
    authLink.AppendFormat("code={0}", vCode);
    authLink.AppendFormat("&client_id={0}", vClientId);
    authLink.AppendFormat("&client_secret={0}", vSecCode);
    authLink.AppendFormat("&redirect_uri={0}", vRedURL);
    authLink.Append("&grant_type=authorization_code");
    UTF8Encoding utfenc = new UTF8Encoding();
    byte[] bytes = utfenc.GetBytes(authLink.ToString());
    Stream os = null;

    webRequest.ContentLength = bytes.Length; // Count bytes to send
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);        // Send it

    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
    if (webResponse == null) { Response.Write("null"); }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    string jsonStr = sr.ReadToEnd().Trim();
}

可能重要的是获取带有服务器端代码的代码,而不是混合客户端代码和服务器端access_token获取脚本。希望这也适合你。