OAuth2令牌,消息:当我尝试使用OAuth连接到Google日历时返回“{”错误“:”access_denied“}'

时间:2013-10-17 06:30:16

标签: asp.net oauth-2.0 google-calendar-api

我正在使用Google Standard Library for ASP.NET来使用Calendar Service版本3,并且我已通过Google API控制台为OAuth 2.0身份验证设置了服务帐户类型。 现在我的名字Objective是使用OAuth2连接日历。因为它对大多数用户来说工作正常,但是因为他们得到错误= 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 "";
}

0 个答案:

没有答案