ChatGPT解决这个技术问题 Extra ChatGPT

How to Logout of an Application Where I Used OAuth2 To Login With Google?

In my application, I implemented Google signout using jsapi.

I used the url https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxxxxx to connect to Google and then https://www.googleapis.com/plus/v1/people/xxxxxx to get user data from google profile.

Now I need to signout the user from Google while clicking a button from my application. How can I implement this in JavaScript, or at least it must ask the Google login page every time the user signs in.

I have tried approval_prompt=force, but seems not to be working.


j
jmort253

Overview of OAuth: Is the User Who He/She Says He/She is?:

I'm not sure if you used OAuth to login to Stack Overflow, like the "Login with Google" option, but when you use this feature, Stack Overflow is simply asking Google if it knows who you are:

"Yo Google, this Vinesh fella claims that vinesh.e@gmail.com is him, is that true?"

If you're logged in already, Google will say YES. If not, Google will say:

"Hang on a sec Stack Overflow, I'll authenticate this fella and if he can enter the right password for his Google account, then it's him".

When you enter your Google password, Google then tells Stack Overflow you are who you say you are, and Stack Overflow logs you in.

When you logout of your app, you're logging out of your app:

Here's where developers new to OAuth sometimes get a little confused... Google and Stack Overflow, Assembla, Vinesh's-very-cool-slick-webapp, are all different entities, and Google knows nothing about your account on Vinesh's cool webapp, and vice versa, aside from what's exposed via the API you're using to access profile information.

When your user logs out, he or she isn't logging out of Google, he/she is logging out of your app, or Stack Overflow, or Assembla, or whatever web application used Google OAuth to authenticate the user.

In fact, I can log out of all of my Google accounts and still be logged into Stack Overflow. Once your app knows who the user is, that person can log out of Google. Google is no longer needed.

With that said, what you're asking to do is log the user out of a service that really doesn't belong to you. Think about it like this: As a user, how annoyed do you think I would be if I logged into 5 different services with my Google account, then the first time I logged out of one of them, I have to login to my Gmail account again because that app developer decided that, when I log out of his application, I should also be logged out of Google? That's going to get old really fast. In short, you really don't want to do this...

Yeh yeh, whatever, I still want to log the user out Of Google, just tell me how do I do this?

With that said, if you still do want to log a user out of Google, and realize that you may very well be disrupting their workflow, you could dynamically build the logout url from one of their Google services logout button, and then invoke that using an img element or a script tag:

<script type="text/javascript" 
    src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

<img src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

window.location = "https://mail.google.com/mail/u/0/?logout&hl=en";

If you redirect your user to the logout page, or invoke it from an element that isn't cross-domain restricted, the user will be logged out of Google.

Note that this does not necessarily mean the user will be logged out of your application, only Google. :)

Summary:

What's important for you to keep in mind is that, when you logout of your app, you don't need to make the user re-enter a password. That's the whole point! It authenticates against Google so the user doesn't have to enter his or her password over and over and over again in each web application he or she uses. It takes some getting used to, but know that, as long as the user is logged into Google, your app doesn't need to worry about whether or not the user is who he/she says he/she is.

I have the same implementation in a project as you do, using the Google Profile information with OAuth. I tried the very same thing you're looking to try, and it really started making people angry when they had to login to Google over and over again, so we stopped logging them out of Google. :)


Thank You for your valuable time and such a large description. But my client have a different opinion. Suppose the user login to the application using his google login from a public system and logged out from the application. He may think that he had logged out from google also but actually not! Any other user using the system later will get access to the google account.
Then your users need to log out of Google too. The point is, they're logging into 2 services. Your users need to learn how to use OAuth. :) I'd suggest educating your client and the users. If you have to, go ahead and show them. It shouldn't take long to implement and then undo later when you realize how much it sucks. :) I didn't believe it for myself until I actually did this and saw how much of a PITA it was to have to log back into Google again every time I logged out of LoopToDo. Consider maybe a message "You're logged out of Vinesh's cool app, don't forget to >log out of Google too
I'm developing a hybrid mobile app (Ionic) with Google OAuth and had the same problem because I wanted to login with different Google accounts but I was always automatically logged in. At the moment I'm making a JSONP asynchronous request to accounts.google.com/logout in order to logout the user but this is a "dirty" trick and spits errors to the console but couldn't find any other working solution. Let me know if someone knows a better way. I don't have the issue of logging out the user from other services since it's a hybrid mobile app contained in a web view.
@jmort253 Yeah I understand that they don't need to provide permissions anymore, but how should I authenticate them again? Please see this question I have made (i am still new to OAuth): stackoverflow.com/questions/37515836/…
@jmort253 However, what if to the user the word "disconnect" implies total log out of the application.. Because it auto logs back in without typing in the credentials again, there is 2 issues; user wonders what happen I just disconnected and it should not have my info and second user won't be able to sign into a different account because it will always auto log in unless the auth provider provides a force-login method. So in this case, logout is desirable so that it can invalidate the cookies and you no longer have to worry about how its managed on the client side.
b
blacktide

You can log out and redirect to your site:

var logout = function() {
    document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://www.example.com";
}

Finally! Thank you! I have been trying for a whole day to find how to logout, to prevent the next user to login as the previous user by just a click, without knowing the email or password...
It doesnt work, because it is enough to open the same page in another tab, and you are logged in again...
Thanks. I have been looking for this for years now.
Yes, it works but there is google warning page which indicates that we are going to be redirected to...
this logs out ALL your google accounts from ALL sites
V
Vinoj John Hosan

For me, it works (java - android)

void RevokeAcess()
{
    try{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
    org.apache.http.HttpResponse response = client.execute(post);
    }
    catch(IOException e)
    {
    }
    CookieManager.getInstance().removeAllCookie(); // this is clear the cookies which tends to same user in android web view
}

You have to call this function in AsyncTask in android


While it is true that this would work, the question is actually asking about JavaScript, not Java.
That sounds freaky that all you need is a token, you can brute force google to forcibly logout everyone.
It wont log out you from device, it will log out only the application(in android).
From looking at some of the google oauth2 docs a typical access token looks like this. "1/fFAGRNJru1FTz70BzhT3Zg" Assuming the "1/" part is just for humans to identify the number easier. You still have two alphabets (upper and lower case) plus ten numerical digits with a length of 22 characters. That's 22^(26*2+10) which equals 1.6990502e+83. Or about the number of atoms in the known universe. Good luck brute forcing that over HTTP. ;)
This does not seem to revoke refresh token, which could be stolen before removing cookies (if it is stored there).
S
Sunil Kumar Singh

To logout from the app only but not the Gmail:

window.gapi.load('auth2', () => {
      window.gapi.auth2
        .init({
          client_id:
            '<Your client id configired on google console>'
        })
        .then(() => {
          window.gapi.auth2
            .getAuthInstance()
            .signOut()
            .then(function() {
              console.log('User signed out.');
            });
        });
    });

I'm using above in my ReactJs code.


works great! Especially if you're on page where gapi is not available anymore, so this actually init and logout.
S
Shivesh Abhishek

You can simply Create a logout button and add this link to it and it will utimately log you out from the app and will redirect to your desired site:

https://appengine.google.com/_ah/logout?continue=http://www.YOURSITE.com

just toggle YOURSITE with your website


C
CamHart

This works to sign the user out of the application, but not Google.

var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});

Source: https://developers.google.com/identity/sign-in/web/sign-in


this won't completely sign out the user from his/her google account. It only destroys the AuthInstance which you used. Your source itself says... "You can enable users to sign out of your app without signing out of Google..."
@RoshanaPitigala updated the answer to specify. This answer is the answer to the title of the question, but once you read the question in more details you understand the title was incorrectly written. This answer works for anyone who made it here according to the title of the question.
R
Rahul Sharma

Ouath just makes the Google instance null, hence it you out of Google. Now that's how the architecture is made. Logging out of Google, if you Logout of your app is a dirty work, but can't help if the requirement stipulates the same. Hence add the following to your signOut() function. My project was an Angular 6 app:

document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:4200";

Here localhost:4200 is the URL of my app. If your login page is xyz.com then input that.


S
Sourabh Kumar Sharma

this code will work to sign out

    <script>
      function signOut() 
      {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {   
        console.log('User signed out.');   
        auth2.disconnect();   
      }); 
        auth2.disconnect();
      } 
    </script>

J
Janakiram

I hope we can achieve this by storing the token in session while logging in and access the token when he clicked on logout.

    String _accessToken=(String)session.getAttribute("ACCESS_TOKEN");
    if(_accessToken!=null)
    {
        StringBuffer path=httpRequest.getRequestURL();
        reDirectPage="https://www.google.com/accounts/Logout?
        continue=https://appengine.google.com/_ah/logout?
        continue="+path;
    }
    response.sendRedirect(reDirectPage);

S
Sean

It looks like Google recently broke something with their revoke stuff (it's started returning 400 errors for us). You now have to call

auth2.disconnect();

In our case we then have to wait a couple of seconds for the disconnect call to complete otherwise the sign-in code will re-authorise before it's done. It'd be good if google returned a promise from the disconnect method.


N
Noor Hossain

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.


u
user3615010
1. Try this code, if you are using onSignIn() function
2.
        <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
       <script>
       function signOut() {
       onLoad();
       var auth2 = gapi.auth2.getAuthInstance();
       auth2.signOut().then(function () {
       console.log('User signed out.');
       if(auth2.isSignedIn)
       {
          auth2.isSignedIn.set(false);
       }
       });
       }
       function onLoad() {
          gapi.load('auth2', function() {
            gapi.auth2.init();
          });
        }
        </script>