adonisjs/ally

Google authentication not setting session

agent306 opened this issue ยท 3 comments

Ally Google authentication callback doesn't seem to set the session, hence auth check always returns false.

I have tried changing the session type to file as well, with no success.

NOTE: Ally works just as expected with facebook. However, this:

const User = use('App/Models/User');

..

async callback({ ally, auth, response, session }) {
    try {
        const providerUser = await ally.driver('google').getUser();

        const userDetails = {
            name: providerUser.getNickname() || null,
            email: providerUser.getEmail() || null,
            profile_pic: providerUser.getAvatar() || null,
        }

        const whereClause = {
            email: providerUser.getEmail()
        }

        const user = await User.findOrCreate(whereClause, userDetails);

        await auth.login(user);

        /*
          Session is definitely set in this line with both providers,
          because this line shows the correct user details
        */
        console.log(auth.user.name); /* Logs the name of the google/facebook user */

        return response.route('login')
        /* I have tried response.redirect('back') as well. Same result. */

        /*
          Response.redirect('back') takes the user back to the login page in facebook's
          case. However, the user is taken back to root (/) in google's case
        */
    } catch (error) {
        session.flash({
            oauth: {
                type: 'error',
                text: 'Failed to login with provider'
            }
        });
        return response.route('login');
    }
}

does not seem to work with google. Works perfectly with facebook though

Hello @agent306,

I want to believe, you are using google chrome.

I had same problem a few months ago, but the solution in this forum solved it https://forum.adonisjs.com/t/auth-session-is-unset-after-auth-then-the-application-redirect/84

https://github.com/iamraphson/adonisjs-hackathon-starter/blob/AdonisJS-4.0/config/session.js#L67

Thank you so much @iamraphson. Setting sameSite: false in config/session.js worked for me.

I looked around a bit and found out that localhost and 127.0.0.1 are treated as two different domains when it comes to sessions by AdonisJS. Hence, when I make a redirection request from http://localhost:3333/google to google OAuth api, it redirects to the callback URI http://127.0.0.1:3333/google/authenticated. So, ultimately, setting the sameSite option to false ignores this domain difference

Hope this helps anyone else facing this issue in the future ๐Ÿ˜„

I looked around a bit and found out that localhost and 127.0.0.1 are treated as two different domains when it comes to sessions by AdonisJS

It's HTTP specification