Google API身份验证

时间:2016-04-05 13:38:19

标签: javascript asp.net-mvc-4 google-oauth google-analytics-api google-api-dotnet-client

我正在尝试了解如何在WEB客户端(JS)上验证用户的流程,然后在我的后端服务器(ASP.NET MVC应用程序)上使用Google API,代表经过身份验证的用户检索用户联系人列表。

这是我使用的当前流程:

1.在HTML中我使用google JS客户端:https://apis.google.com/js/client.js

function auth(callback) {
        var config = {
          'client_id': '***********',
          'scope': 'https://www.googleapis.com/auth/contacts.readonly'          
        };
        config.immediate = true;
        gapi.auth.authorize(config, function (authResult) {
            if (authResult && !authResult.error) {
                callback();
            }
            else {
                config.immediate = false;
                gapi.auth.authorize(config, function (response) {
                    //Here I send access_token to back-end using HTTPS
                });
            }
        });
      }

2.然后我使用gapi.auth.getToken()并将其发送到后端服务器(使用HTTPS AJAX调用)
3.然后在服务器上,我在控制器中有以下代码:

public JsonResult Get(TokenModel model)
        {
            //Custom store for access_token
            var myStore = new MyStore(NewtonsoftJsonSerializer.Instance.Serialize(new TokenResponse() { Issued = DateTime.Now, ExpiresInSeconds = 3600, TokenType = "Bearer", AccessToken = model.access_token }));

            string[] Scopes = { PeopleService.Scope.ContactsReadonly };
            ClientSecrets secrets = new ClientSecrets() { ClientId = "******", ClientSecret = "******" };
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                secrets,
                Scopes,
                "user",
                CancellationToken.None,
                myStore 
                ).Result;

            var service = new PeopleService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

           List<string> result = GetPeople(service, null);

            return Json(result);
        }

问题:

  1. 这是正确的流量,在我的情况下GoogleWebAuthorizationBroker是否是在服务器上使用的正确类?
  2. 为什么以及GoogleWebAuthorizationBroker如何model.access_token = null打开一个新的浏览器窗口进行身份验证?
  3. 为什么当令牌无效时(​​例如:“dasdasdasdas”),AuthorizeAsync方法返回看起来绝对有效的UserCredential,但是当向google api发出实际请求时会发生异常。
  4. 从上面的流程来看,我可以获得“刷新令牌”供以后使用(据我所知,我需要以某种方式自己生成它,使用access_token + secret key)。
  5. 谢谢!

0 个答案:

没有答案