gpt4 book ai didi

asp.net-mvc - 为什么我没有收到来自 Google OAuth 请求的 RefreshToken?

转载 作者:行者123 更新时间:2023-12-04 09:32:10 29 4
gpt4 key购买 nike

我正在尝试将 Google 日历集成到我的应用程序中,但我在传递 RefreshToken 的 OAuth 授权方面遇到了一些问题。我收到一个没有问题的 AccessToken,但 RefreshToken 属性为空。请参阅标记为“ERROR HERE:”的行,了解我遇到的问题

我的 Asp.Net MVC Controller (名为 OAuthController)如下所示:

    public ActionResult Index()
{
var client = CreateClient();
client.RequestUserAuthorization(new[] { "https://www.googleapis.com/auth/calendar" }, new Uri("http://localhost/FL.Evaluation.Web/OAuth/CallBack"));

return View();
}

public ActionResult CallBack()
{

if (string.IsNullOrEmpty(Request.QueryString["code"])) return null;

var client = CreateClient();

// Now getting a 400 Bad Request here
var state = client.ProcessUserAuthorization();

// ERROR HERE: The RefreshToken is NULL
HttpContext.Session["REFRESH_TOKEN"] = Convert.ToBase64String(Encoding.Unicode.GetBytes(state.RefreshToken));

return JavaScript("Completed!");
}

private static WebServerClient CreateClient()
{
return
new WebServerClient(
new AuthorizationServerDescription()
{
TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"),
AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"),
ProtocolVersion = ProtocolVersion.V20
}
, _GoogleClientId, _GoogleSecret);
}

我在 Google 的 API 文档中看到,我需要确保 access_type请求设置为 offline用于发送 RefreshToken。如何在我的身份验证器请求中设置此值?

最佳答案

经过几个小时的摆弄 DotNetOpenAuth 和为 .Net 发布的 Google APIs,我无处可去。我决定绕过库,直接使用原生 HttpRequest 和 HttpResponse 对象访问 Google REST API。我的 MVC Controller 的清理代码如下:

    private static string _GoogleClientId = "CLIENT_ID";
private static string _GoogleSecret = "SECRET";
private static string _ReturnUrl = "http://localhost/OAuth/CallBack";

public ActionResult Index()
{
return Redirect(GenerateGoogleOAuthUrl());
}

private string GenerateGoogleOAuthUrl()
{

//NOTE: Key piece here, from Andrew's reply -> access_type=offline forces a refresh token to be issued
string Url = "https://accounts.google.com/o/oauth2/auth?scope={0}&redirect_uri={1}&response_type={2}&client_id={3}&state={4}&access_type=offline&approval_prompt=force";
string scope = UrlEncodeForGoogle("https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly").Replace("%20", "+");
string redirect_uri_encode = UrlEncodeForGoogle(_ReturnUrl);
string response_type = "code";
string state = "";

return string.Format(Url, scope, redirect_uri_encode, response_type, _GoogleClientId, state);

}

private static string UrlEncodeForGoogle(string url)
{
string UnReservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
var result = new StringBuilder();

foreach (char symbol in url)
{
if (UnReservedChars.IndexOf(symbol) != -1)
{
result.Append(symbol);
}
else
{
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
}

return result.ToString();
}

class GoogleTokenData
{
public string Access_Token { get; set; }
public string Refresh_Token { get; set; }
public string Expires_In { get; set; }
public string Token_Type { get; set; }
}

public ActionResult CallBack(string code, bool? remove)
{

if (remove.HasValue && remove.Value)
{
Session["GoogleAPIToken"] = null;
return HttpNotFound();
}

if (string.IsNullOrEmpty(code)) return Content("Missing code");

string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(_ReturnUrl);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}";

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, code, _GoogleClientId, _GoogleSecret, redirect_uri_encode, 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<GoogleTokenData>(result);
Session["GoogleAPIToken"] = tokenData.Access_Token;

return JavaScript("Refresh Token: " + tokenData.Refresh_Token);

}

非常感谢 Kelp 在这个片段中提供了一些代码。

关于asp.net-mvc - 为什么我没有收到来自 Google OAuth 请求的 RefreshToken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346355/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com