How to get access token for google oauth?

前端 未结 5 1865
离开以前
离开以前 2021-02-05 21:30

I am using C# (ASP.NET). I want to use Google OAuth for accessing the user profile detail in my app. I successfully got the authorization code but having a problem in getting th

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 22:21

    public string ReceiveTokenGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)
    {
        string postString = "code=" + code + "&client_id=" + GoogleWebAppClientID + @"&client_secret=" + GoogleWebAppClientSecret  + "&redirect_uri=" + RedirectUrl;
    
        string url = "https://accounts.google.com/o/oauth2/token";
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
    
        UTF8Encoding utfenc = new UTF8Encoding();
        byte[] bytes = utfenc.GetBytes(postString);
        Stream os = null;
        try
        {
            request.ContentLength = bytes.Length;
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
        }
        catch
        { }
        string result = "";
    
        HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        result = responseStreamReader.ReadToEnd();
    
        return result;
    }
    

提交回复
热议问题