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

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

根据这个documentation ,接收 OAuth 访问 token 的过程很简单。我想查看准备好接受 OAuth 2.0 访问 token 的所有可用 API 端点的列表。但对于我目前的需求,我想以某种方式收到 usernameemail使用 OAuth 2.0 访问 token 的用户。

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

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

但无法从该端点接收数据:
https://www.googleapis.com/userinfo/email

我尝试了基于 header 和基于查询字符串的传递单个访问 token 的方法。这是我试过的标题:
Authorization: OAuth My_ACCESS_TOKEN

我什至尝试了 OAuth 1.0 版本的 Authorization header ,但是……例如,在 OAuth 2.0 中,我们没有 secret 访问 token 。 Google 在他的 OAuth 2.0 实现中使用不记名 token ,因此不需要额外的凭据。

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

最佳答案

我找到了我正在寻找的答案。我必须将 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的证明来自用户的 token ,然后需要将其转换为 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;
    }
}

同样,这是测试代码,只是为了让它发挥作用,我不建议在生产环境中按原样使用它。

关于authentication - 使用 OAuth 2.0 的 Google 实验性实现来访问现有的 API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408971/

相关文章:

php - Laravel Passport 打印个人访问 token

rest - Web UI 到一个 Restful 界面,好主意吗?

javascript - 使用 HTTP 身份验证自动登录的 GreaseMonkey 脚本

php - 将用户存储为对象是否有意义?

php - 使用 oAuth 处理多个谷歌登录用户

java - 如何使用 JAVA API 从 BigQuery 查询数据

android - 如何从开发者控制台获取 google-services.json?

google-maps - 如何覆盖 Xamarin Android Manifest 中的键

ios - 为一个选项卡设置不同的 View Controller

mysql - 如何将 Power BI Desktop 连接到需要身份验证的远程 MySql 服务器