使用谷歌的实验实现的OAuth 2.0访问现有的API端点 [英] Using Google experimental implementation of OAuth 2.0 to access existing API endpoints

查看:99
本文介绍了使用谷歌的实验实现的OAuth 2.0访问现有的API端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个文档,接收的OAuth的过程访问令牌很简单。我希望看到所有可用的API端点准备接受的OAuth 2.0访问令牌的列表。但对于我目前的需求,我想以某种方式获得用户名电子邮件使用OAuth 2.0访问令牌的用户。

According to this documentation, process of receiving OAuth access token is straightforward. I would like to see a list of all available API endpoints that is ready to accept OAuth 2.0 access token. But for my current needs i would like to somehow receive username and email of a user using OAuth 2.0 access token.

我成功可以接收,例如,从这个端点数据:

I successfully can receive, for example, data from this endpoint:

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

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

But unable to receive data from this endpoint:

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

我试图传递一个访问令牌的两个头基和查询字符串基的方法。这里是一个头我想:

I tried both header-base and querystring-base approaches of passing single access token. Here is a header i tried:

Authorization: OAuth My_ACCESS_TOKEN

和我甚至尝试的OAuth 1.0版本的授权头,但是......在OAuth 2.0用户,我们没有秘密访问令牌,例如。谷歌使用承载令牌在他执行的OAuth 2.0,因此不需要额外的凭据。

And I even tried OAuth 1.0 version of Authorization header, but... in OAuth 2.0 we do not have secret access token, for instance. Google use bearer tokens in his implementation of OAuth 2.0, so no additional credentials are required.

任何成功接收用户名和电子邮件使用谷歌的OAuth 2.0吗?

Anyone successfully received username and email using Google OAuth 2.0?

推荐答案

我发现我一直在寻找答案。我不得不PHP转换为MVC,但pretty容易:

I found the answer I was looking for. I had to convert PHP to MVC, but pretty easy:

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

我的MVC 登录沙箱code看起来像下面这样。
(使用JSON.Net HTTP://json.$c$cplex.com/

My MVC Login sandbox code looks like the following. (using 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 返回的授权证明从用户,然后必须转令牌成验证(的accessToken)访问资源。
我的MVC OAuthVerify 则是这样的:

The code returned is proof of Authorization token from the user, which then needs to be turn into a Authentication (accessToken) to access resources. My MVC OAuthVerify then looks like:

    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的程序需要它。

To complete how everything works, I've included the HttpClient utility I created in case anyone needed it.

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

同样,这也是考验code只是为了得到它的工作,我不推荐使用这种作为,是在生产环境中。

Again, this is test code just to get it to function, I do not recommend using this as-is in a production environment.

这篇关于使用谷歌的实验实现的OAuth 2.0访问现有的API端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆