Phu Nguyen Phu Nguyen - 3 months ago 23
Javascript Question

Google Drive SDK OAuth2 with multiple user account

If a user has several accounts in their Google, the user has to choose an account as it doesn't remember which account the user chose previously.


enter image description here


I have managed to make an OAuth2 authentication using these codes and the configurations guided from https://developers.google.com/api-client-library/javascript/features/authentication#specifying-your-client-id-and-scopes

this.authenticate = function(){
gapi.load('client:auth2',authorize);
}
function authorize(){
gapi.client.setApiKey(API_KEY);
gapi.auth2.init({
client_id: CLIENT_ID,
scope: SCOPES
}).then(function(authResult){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signIn().then(afterSignIn);
});
}
function afterSignIn(){
console.log('authenticated successfully');
$rootScope.authenticated = true;
gapi.client.load('drive', 'v3',function(){
$rootScope.$broadcast('authenticated');
});
}


I have tried these options of
GoogleAuth.signIn()
:

auth2.signIn({
'prompt': '**promtOption**'
})...


  • none
    : it doesn't authenticate
  • login
    : does the same as
    select_account

  • consent
    : does the same as
    select_account
    , it additionally asks for offline use permission...
  • select_account
    : same problem as signing in without
    options


    How can I make the program remember the user selection?

  • Answer

    Calling auth2.signIn() will always prompt the user to sign in, even if they are already signed in. Before doing that, check to see if they are already signed in using auth2.currentUser.get().isSignedIn(). Here's a modified version of your code:

    function authorize(){
        gapi.client.setApiKey(API_KEY);
        gapi.auth2.init({
            client_id: CLIENT_ID,
            scope: SCOPES
        }).then(function(authResult){
            var auth2 = gapi.auth2.getAuthInstance();
            var user = auth2.currentUser.get();
            if (user.isSignedIn()) {
              afterSignIn();
            } else {
              auth2.signIn().then(afterSignIn);
            }
        });
    }
    
    Comments