使用Google实验性的OAuth 2.0实现访问现有的API端点

Dmi*_*ich 7 authentication oauth google-api single-sign-on oauth-2.0

根据此文档,接收OAuth访问令牌的过程非常简单.我希望看到已准备好接受OAuth 2.0访问令牌的所有可用API端点的列表.但对于我目前的需求,我想以某种方式获得usernameemail使用OAuth 2.0访问令牌的用户.

我成功地可以接收来自此端点的数据:

https://www.google.com/m8/feeds/contacts/default/full
Run Code Online (Sandbox Code Playgroud)

但无法从此端点接收数据:

https://www.googleapis.com/userinfo/email
Run Code Online (Sandbox Code Playgroud)

我尝试了传递单一访问令牌的header-base和querystring-base方法.这是我试过的标题:

Authorization: OAuth My_ACCESS_TOKEN
Run Code Online (Sandbox Code Playgroud)

我甚至尝试过OAuth 1.0版本的Authorization标头,但是......在OAuth 2.0中,我们没有秘密访问令牌.Google在其OAuth 2.0实施中使用了承载令牌,因此无需其他凭据.

是否有人使用Google OAuth 2.0成功收到用户名和电子邮件?

Eri*_*ips 1

我找到了我正在寻找的答案。我必须将 PHP 转换为 MVC,但非常简单:

http://codecri.me/case/430/get-a-users-google-email-address-via-oauth2-in-php/

我的 MVCLogin沙箱代码如下所示。(使用 JSON.Net http://json.codeplex.com/

public ActionResult Login()
    {
        string url = "https://accounts.google.com/o/oauth2/auth?";
        url += "client_id=<google-clientid>";
        url += "&redirect_uri=" +
          // Development Server :P 
          HttpUtility.UrlEncode("http://localhost:61857/Account/OAuthVerify");
        url += "&scope=";
        url += HttpUtility.UrlEncode("http://www.google.com/calendar/feeds/ ");
        url += HttpUtility.UrlEncode("http://www.google.com/m8/feeds/ ");
        url += HttpUtility.UrlEncode("http://docs.google.com/feeds/ ");
        url += HttpUtility.UrlEncode("https://mail.google.com/mail/feed/atom ");
        url += HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email ");
        url += HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.profile ");
        url += "&response_type=code";

        return new RedirectResult(url);
    }
Run Code Online (Sandbox Code Playgroud)

返回的是用户的tokencode证明,然后需要将其转换为(accessToken)来访问资源。我的 MVC看起来像:AuthorizationAuthenticationOAuthVerify

    public ActionResult AgentVerify(string code)
    {
        JObject json;

        if (!string.IsNullOrWhiteSpace(code))
        {
            NameValueCollection postData = new NameValueCollection();
            postData.Add("code", code);
            postData.Add("client_id", "<google-clientid>");
            postData.Add("client_secret", "<google-client-secret>");
            postData.Add("redirect_uri", "http://localhost:61857/Account/OAuthVerify");
            postData.Add("grant_type", "authorization_code");

            try
            {   
                json = JObject.Parse(
                  HttpClient.PostUrl(
                    new Uri("https://accounts.google.com/o/oauth2/token"), postData));
                string accessToken = json["access_token"].ToString();
                string refreshToken = json["refresh_token"].ToString();
                bool isBearer = 
                  string.Compare(json["token_type"].ToString(), 
                                 "Bearer", 
                                 true, 
                                 CultureInfo.CurrentCulture) == 0;

                if (isBearer)
                {
                    json = JObject.Parse(
                      HttpClient.GetUrl(
                        new Uri("https://www.googleapis.com/oauth2/v1/userinfo?alt=json"),
                      accessToken));
                    string userEmail = json["email"].ToString();
                }
                return View("LoginGood"); 
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH
            }
        }
        return View("LoginBad");
    }
Run Code Online (Sandbox Code Playgroud)

为了完成一切的工作原理,我添加了我创建的 HttpClient 实用程序,以防有人需要它。

public class HttpClient
{
    public static string GetUrl(Uri url, string OAuth)
    {
        string result = string.Empty;

        using (WebClient httpClient = new WebClient())
        {
            httpClient.Headers.Add("Authorization","OAuth " + OAuth);
            result = httpClient.DownloadString(url.AbsoluteUri);
        }

        return result;
    }

    public static string PostUrl(Uri url, NameValueCollection formData)
    {
        string result = string.Empty;

        using (WebClient httpClient = new WebClient())
        {
            byte[] bytes = httpClient.UploadValues(url.AbsoluteUri, "POST", formData);
            result = Encoding.UTF8.GetString(bytes);
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

再次强调,这是测试代码,只是为了使其正常运行,我不建议在生产环境中按原样使用此代码。