Asp.net mvc Google OAuth2:在.NET中为刷新和承载令牌交换访问代码
我正在构建一个MVC应用程序,在这个应用程序中,用户必须登录Google才能提供对其信息的离线访问。 我通过JavaScript从视图中获取访问代码,并将其发送到控制器。 从控制器我向谷歌Api发出POST请求,但我一直收到一个错误的请求 有人成功地实现了这一点吗Asp.net mvc Google OAuth2:在.NET中为刷新和承载令牌交换访问代码,asp.net-mvc,post,oauth-2.0,google-oauth,Asp.net Mvc,Post,Oauth 2.0,Google Oauth,我正在构建一个MVC应用程序,在这个应用程序中,用户必须登录Google才能提供对其信息的离线访问。 我通过JavaScript从视图中获取访问代码,并将其发送到控制器。 从控制器我向谷歌Api发出POST请求,但我一直收到一个错误的请求 有人成功地实现了这一点吗 string baseUri = "https://www.googleapis.com/oauth2/v3/token/"; string parCode = string.Format("code=
string baseUri = "https://www.googleapis.com/oauth2/v3/token/";
string parCode = string.Format("code={0}",Code);
string parSecret = "client_secret=******";
string parId = "client_id=*******************";
string parRedirect = "redirect_uri=https://localhost:44301";
string postData = string.Format("{0}&{1}&{2}&{3}", parCode, parRedirect, parId, parSecret);
Uri postUri = new Uri(baseUri);
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] data = encoding.GetBytes (postData);
var request = (HttpWebRequest)WebRequest.Create(baseUri);
request.Method = "POST";
request.ContentType = " application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
HttpWebResponse response;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
您缺少grant_类型参数,该参数应设置为AUTHORITION_code。您还应该对各个参数值进行表单编码。对于后者,可以方便地使用NameValueCollection,如中所示:
现在postData将被正确编码,以便在表单POST中使用。这里有一个MVC示例项目,但它用于使用Google日历,它可能仍然会给您一些启发,我错过了grant_type参数。我已经解决了这个问题,但是表单编码到底是什么呢?我添加了示例代码来演示forn编码
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("code", Code);
//...etc. for the other parameters
string postdata = outgoingQueryString.ToString();