问题
I'm trying to understand the flow how to authenticate user on WEB client (JS), and then use Google API on my back-end server (ASP.NET MVC application), on behalf of authenticated user for retrieving users contacts list.
Here the current flow that I use:
1.In HTML I use google JS client: 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.Then I use gapi.auth.getToken() and send it to back-end server (Using a HTTPS AJAX call)
3.Then on server I have the following code in controller:
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);
}
Questions:
- Is it the correct flow and does
GoogleWebAuthorizationBroker
is a correct class to use on server in my case? - Why and HOW
GoogleWebAuthorizationBroker
opens a new browser window for authentication, in casemodel.access_token = null
? - Why when the token is not valid (ex: “dasdasdasdas”),
AuthorizeAsync
method returns me the UserCredential that looks absolutely valid, but then the exception occurs when make actual request to google api. - How from the above flow, I can get “refresh token” for later use (as I understand, I need somehow generate it myself, using access_token + secret key).
Thanks!
来源:https://stackoverflow.com/questions/36428026/authentication-for-google-api