我正在使用 Google ASP.NET 标准库来使用日历服务版本 3,并且我已经通过 Google API 控制台为 OAuth 2.0 身份验证设置了服务帐户类型。现在我的名字目标是使用 OAuth2 连接日历。因为它对大多数用户来说工作正常,但对于一些受限用户来说却遇到了问题,因为他们得到了 error=access_denied。我正在使用以下代码从 OAuth 2 进行身份验证
private static string PrivateFeed = @"https://www.googleapis.com/auth/calendar";
public static string GenerateGoogleOAuthURL(String ReturnUrl)
{
string Url = "https://accounts.google.com/o/oauth2/auth?scope={0}&redirect_uri={1}&response_type={2}&client_id={3}&state={4}&access_type={5}&approval_prompt={6}";
string scope = UrlEncodeForGoogle(PrivateFeed).Replace("%20", "+");
string redirect_uri_encode = UrlEncodeForGoogle(ReturnUrl);
string response_type = "code";
string state = "";
string access_type = "offline";
string approval_prompt = "force";
String ClientID = ConfigurationManager.AppSettings["clientID"].ToString();
return string.Format(Url, scope, redirect_uri_encode, response_type, ClientID, state, access_type, approval_prompt);
}
在返回重定向页面时,我使用以下代码获取刷新令牌:-
private String ExchangeCodeWithAccessAndRefreshToken()
{
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = string.Empty;
redirect_uri_encode = UrlEncodeForGoogle(Convert.ToString(Session["URL"]));
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}";
string Code = Request.QueryString["Code"];
String ClientID = ConfigurationManager.AppSettings["clientID"].ToString();
String ClientSecret = ConfigurationManager.AppSettings["clientSecret"].ToString();
try
{
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = string.Empty;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, Code, ClientID, ClientSecret, 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();
}
if (!string.IsNullOrEmpty(result))
{
var jsonSerializer = new JavaScriptSerializer();
var tokenData = jsonSerializer.Deserialize<GoogleTokenModel>(result);
return tokenData.Refresh_Token;
}
}
catch (Exception ex)
{
}
return "";
}