secondman
secondman

Reputation: 3277

Can I use Laravel Sanctum Token Authentication with Nuxt/Auth?

I'm attempting to get Token auth with Sanctum working with nuxt/auth but several of the functions don't seem to work.

I have an endpoint that authenticates the user via username/email and password, no issues on the API side of things, it returns a personal access token with the correct scopes.

However, in nuxt/auth the methods setUserToken and setUser should both be able to handle logging in a user, granted in different ways, but neither method is completing what it's supposed to do.

this.$auth.loginWith('sanctum', {
    data: this.form
}).then((response) => {
    // this should set the token to storage
    // then fetch the user with the token 
    // but it only sets the token to storage
    this.$auth.setUserToken(response.data)
    .then(() => {
        // so I have to fetch the user myself with VuexORM
        this.user.api().get('/me')
        .then((result) => {
            // my user is set to the model, but not to auth
            this.$auth.setUser(result.response.data) // sets user but won't set loggedIn to true.
        })
    })
}).catch((e) => {
    console.log(e.message)
})

So at this point with all this failing, am I missing something? Or should I just skip nuxt/auth altogether?

Upvotes: 2

Views: 2655

Answers (1)

fevid
fevid

Reputation: 743

It works with Nuxt/Auth but using the sanctum strategy given by Nuxt/Auth docs uses cookie based authentication, you can use local strategy for token based authentication with sanctum.

You don't need to setUserToken or setUser manualy, Nuxt/Auth will do it for you if you have configured it correctly.

you can configure it like below, change it accoring to your endpoints:

  auth: {
    strategies: {
      local: {
        token: {
          property: 'token',
        },
        user: {
          property: false,
        },
        endpoints: {
          login: { url: '/auth/login', method: 'post' },
          logout: { url: '/auth/logout', method: 'post' },
          user: { url: '/auth/user', method: 'get' }
        }
      }
    }
  },

and make sure to return token after logging in the user in Laravel via ['token' => $user->createToken('login')->plainTextToken]

Upvotes: 6

Related Questions