如何从asp.net中的刷新令牌Google获取访问令牌?
您不应该根据特定的生命周期来设计您的应用程序 访问令牌。假设它们(非常)短暂。
然而,在成功完成OAuth2安装后 在应用程序流程中,您将获得刷新令牌。这个刷新 令牌永不过期,您可以使用它来交换它以进行访问 令牌根据需要。保存刷新令牌,并使用它们来获取访问权限 按需令牌(然后应立即用于访问) 用户数据)。
答案 0 :(得分:0)
private bool GetNewAccessToken(GoogleTokenModel GoogleTokenModelObj)
{
try
{
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "refresh_token";
string redirect_uri_encode = UrlEncodeForGoogle(ReturnUrl);
string data = "client_id={0}&client_secret={1}&refresh_token={2}&grant_type={3}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, ClientID, ClientSecret, GoogleTokenModelObj.Refresh_Token, grant_type);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
var jsonSerializer = new JavaScriptSerializer();
var TokenData = jsonSerializer.Deserialize<GoogleTokenModel>(result);
GoogleTokenModelObj.Access_Token = TokenData.Access_Token;
if (TokenData.Refresh_Token != null)
GoogleTokenModelObj.Refresh_Token = TokenData.Refresh_Token;
//GoogleTokenModelObj.LastAccessDateTime = DateTime.Now;
//Update the refresh and access token in DB for next login usage
//GoogleCalendarManager.UpdateRefreshTokenInGoogleAppointmentOAuth(GoogleTokenModelObj);
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "App_Data\\XMLfile.xml");
XmlDoc.DocumentElement.SelectSingleNode("//User[@UserID='1']").Attributes["AccessToken"].Value = TokenData.Access_Token;
XmlDoc.DocumentElement.SelectSingleNode("//User[@UserID='1']").Attributes["RefreshToken"].Value = TokenData.Refresh_Token;
XmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "App_Data\\XMLfile.xml");
return true;
}
catch
{
return false;
}
}