0
  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 页面中放置了一个谷歌登录按钮,在它的回调中获得了验证代码来调用包含上述代码的 ajax web 服务。但是我在 GetResponse() 上收到错误 400,我不知道为什么。任何机构都可以帮助我吗?

4

1 回答 1

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 获取脚本。希望这对你也有效。

于 2013-11-30T13:00:44.830 回答