How to check if user is logged in or not with “Google Sign In” (OAuth 2.0)

前端 未结 4 990
[愿得一人]
[愿得一人] 2020-12-15 22:25

I am implementing Google log in for the first time as described here and here.

I am using HTML with Javascript.

The problem that needs solving is as follows:

4条回答
  •  Happy的楠姐
    2020-12-15 22:44

    You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)

    function onSignIn(googleUser) 
    {
      var profile = googleUser.getBasicProfile();
      console.log('ID: ' + profile.getId()); 
      console.log('Name: ' + profile.getName());
      console.log('Image URL: ' + profile.getImageUrl());
      console.log('Email: ' + profile.getEmail());
      
      var myUserEntity = {};
      myUserEntity.Id = profile.getId();
      myUserEntity.Name = profile.getName();
      
      //Store the entity object in sessionStorage where it will be accessible from all pages of your site.
      sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
    
      alert(profile.getName());   
    }
    
    function checkIfLoggedIn()
    {
      if(sessionStorage.getItem('myUserEntity') == null){
        //Redirect to login page, no user entity available in sessionStorage
        window.location.href='Login.html';
      } else {
        //User already logged in
        var userEntity = {};
        userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
        ...
        DoWhatever();
      }
    }
    
    function logout()
    {
      //Don't forget to clear sessionStorage when user logs out
      sessionStorage.clear();
    }

    Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.

提交回复
热议问题