Authenticate Issues

Hello,

Note - when I say refreshed the dapp/page this also means authenticated was called again.

I started with the basic authentication sample. It worked but I noticed that if I refresh the page a few time every other authentication call fails.

I am working on my own dapp for the hacathon and was able to login at first. However now everytime I try to authenticate I receive a 400 with err: {“message”:“Invalid session token”,“code”:209}

In Moralis I deleted the session record for the user and tried again - same result.
In Moralis I re-started the server and refreshed the dapp - same result.
I logged out of Metamask, logged back in and refreshed the dapp - same result.

So in Moralis I deleted all the rows associated with the ethAddress and refreshed the dapp - IT WORKED! but I had an error in the way I was processing the result object so I refreshed the page and received the {“message”:“Invalid session token”,“code”:209} error again.

How can I call authenticate again without receiving the error? Is there a different path for refreshing the information - or checking that it is already authenticated?

Thank you,

David

Hey!

Let me have a look at your code please :slight_smile:
When posting code please ensure it’s formatted (check this guide).

The wrapper:

/// moralis.js
/// Asset DAO project - David B. Goodrich
/// Defines a class that wraps moralis methods
!(function() {
   'use strict';

   /// Define wrapper class - initiate Moralis when called.
   var MoralisWeb3 = function () {
     console.log('MoralisWeb3 instance created ...');

     Moralis.initialize("[REMOVED FOR POST]"); 
     Moralis.serverURL = "https://51x9pnsvopbn.moralis.io:2053/server"; 
   }

   /// Perform Moralis authentication, when successfull returns user
   /// related information.
   MoralisWeb3.prototype.login = function () {
       return Moralis.Web3.authenticate();
   }

   // CommonJS - add module to global module / windows for
   // easy use in other modules.
   if (typeof exports === 'object' && typeof module !== 'undefined') {
       module.exports = new MoralisWeb3;
   } else if (typeof window !== 'undefined') {
       window.MoralisWeb3 = new MoralisWeb3;
   }
 })();

Called by this block (typescript, Angular 11):

    /// Handle login request for dAPP
    /// @return Promise<User>
    login () : Promise<User> {
        var self = this;

        // Use Moralis as user authenticator to authenticate via wallet.
        return MoralisWeb3.login().then((result:any) => {
            console.log('Moralis returned user: ' + JSON.stringify(result));
            let t = result.toJSON();
            let user : User = new User();

            // TODO Map to Moralis response object correctly
            user.createdAt = t.createdAt;
            user.ethAddress = t.ethAddress;
            user.objectId = t.objectId;
            user.sessionToken = t.sessionToken;
            user.updatedAt = t.updatedAt;
            user.userId = t.userId;
            user.userName = t.userName;

            // Persist user locally.
            self.setUser(user);

            return user;
        })
        .catch((err:any) => {
            console.log("Login Error: " + JSON.stringify(err));
        });
    }

NOTE: I have put break points at every point in the wrapper class and they are called every time. The code in the “then” block is only called when I log into Moralis and delete records related to the wallet address. Once Moralis has authenticed the first time, followup calls return: 400 (Bad Request) {“message”:“Invalid session token”,“code”:209}

The return code indicates I am sending something incorrectly in my request, but it does succeed for the the first call.

Thank you,

David

Hi. Thanks for reminding us of this error. This “invalid session token” error occurs whenever a user is logged in multiple times without logging out. The current user is stored locally and is persisted between sessions so there may already be a logged in user when the page loads.

This is a known issue. The error message could be better at least. There is a very simple workaround however so this is currently a low priority bug.

Workaround

  • check for the current user Moralis.User.current()
  • if there is no current user log in
  • if the user is already authenticated
    • Either do nothing, or
    • Log the current user out and re-authenticate

For example:

      async function login() {
        let user = Moralis.User.current();
        if (!user) {
          user = await Moralis.Web3.authenticate();
        }
        console.log("logged in user:", user);
      }

If you wanted to be more thorough you could add some additional validation to check that the existing current user is still the same person.

2 Likes

Thank you! I will make this update.

@mayjer This fix solved the problem.

1 Like