我正在尝试了解如何在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);
}
问题:
GoogleWebAuthorizationBroker
是否是在服务器上使用的正确类? GoogleWebAuthorizationBroker
如何model.access_token = null
打开一个新的浏览器窗口进行身份验证? AuthorizeAsync
方法返回看起来绝对有效的UserCredential,但是当向google api发出实际请求时会发生异常。 谢谢!