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

时间:2011-03-23 17:05:51

标签: authentication oauth google-api single-sign-on oauth-2.0

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

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

https://www.google.com/m8/feeds/contacts/default/full

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

https://www.googleapis.com/userinfo/email

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

Authorization: OAuth My_ACCESS_TOKEN

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

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

2 个答案:

答案 0 :(得分:1)

我找到了我想要的答案。我不得不将PHP转换为MVC,但非常简单:

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

我的MVC Login沙箱代码如下所示。 (使用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);
    }

返回的code证明了来自用户的Authorization令牌,然后需要将其转换为Authentication(accessToken)来访问资源。 我的MVC OAuthVerify看起来像:

    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");
    }

为了完成所有工作的方式,我已经包含了我创建的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;
    }
}

同样,这是测试代码只是为了使其正常运行,我不建议在生产环境中使用它。

答案 1 :(得分:0)

试试这个:

curl -k https://www.googleapis.com/userinfo/email -H“授权:OAuth 1 / g5_039aCIAfEBuL7OCyB31n1URYU5tUIDudiWKuxN1o”

输出:email=name@gmail.com& isVerified = tru