How to get access token for google oauth?

前端 未结 5 1787
离开以前
离开以前 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 21:57

    As I had similar problems in the process of implementing Google auth, I will post the code that works.. The last mentioned problem: error (400) Bad request could be caused by leading '?' in the above code..

     string codeClient = "code="+ t +"&client_id=number.apps.googleusercontent.com&";
     string secretUri = "client_secret=yoursecret&" + "redirect_uri=path&"
          + "grant_type=authorization_code";
     postString = codeClient + secretUri;
    
     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
     { }
    
     try
     {
          HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse();
          Stream responseStream = webResponse.GetResponseStream();
          StreamReader responseStreamReader = new StreamReader(responseStream);
          result = responseStreamReader.ReadToEnd();//parse token from result
    

提交回复
热议问题