AdonisJS 6 Session Authentication in 15 Minutes

In this lesson, we'll learn how to add authentication to a new AdonisJS 6 application using the session guard. In these 15 minutes, you'll learn how to register a user, logout a user, verify a user's credentials and log them in, and more.

Published
Apr 18
Duration
15m 18s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Join The Discussion! (2 Comments)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 1 month ago

    This is a great walkthrough on session based auth. One of the things I'm struggling with is using Ally to authenticate via Google and then convert that into an authorized session. I have the Google auth flow working as expected. I just don't know how to use that data to flow into a user session. Have you seen any resources on this?

    1

    Please sign in or sign up for free to reply

    1. Commented 1 month ago

      Thank you, Mark!! We haven't discussed social authentication with AdonisJS 6 in any of our lessons quite yet. But, once you get the user details from Google, you'll want to determine if you have a matching user already in your database, and if not, create that user. Once you've either found the matching user or created the new user, you can log them in using AdonisJS Auth.

      router.get('/google/callback', async ({ ally, auth }) => {
        const google = ally.use('google')
      
        // ... validity checks
      
        const googleUser = await google.user()
      
        const appUser = await User.updateOrCreate({
          // attempt to find a user with the matched Google Id
          googleId: googleUser.id
        }, {
          // no match found? merge googleId with this data and create the user
          // add any other data your user needs here
          email: googleUser.email,
          token: googleUser.token.token,
          refreshToken: googleUser.token.refreshToken
        })
      
        // once we have the user, log them in
        await auth.use('web').login(user)
      })
      Copied!

      Hope this helps!

      1

      Please sign in or sign up for free to reply