Nuxt Auth - Sanctum

11th November 2020

The Nuxt auth-next plugin has support for Laravel Sanctum pre-built in. However, if you require multi device support through the use of sanctum's built in personal access tokens, then a different authentication method is needed.

To do this, we'll need to use the built in cookie scheme. The endpoints can be set to whichever routes you have available on your API, but the token information will need to be specified. We need to tell Nuxt to use the token property as the Authorization Bearer.

auth: {
  cookie: {
    options: {
      maxAge: 43200 // 12 hours
    }
  },
  redirect: {
    login: '/login',
    logout: '/',
    callback: '/',
    home: '/dashboard',
  },
  strategies: {
    default: {
      endpoints: {
        csrf: { url: 'csrf-cookie' },
        login: { url: 'login', method: 'post' },
        logout: { url: 'logout', method: 'delete' },
        user: { url: 'auth', method: 'get' },
      },
      scheme: 'cookie',
      token: {
        name: 'Authorization',
        global: true,
        property: 'token',
        required: 'true,
        type: 'Bearer',
      }
    },
  }
}

The login method of our API needs to return json containing the plain text token.

[login validation]

$token = $user->createToken($name);

return response()->json([
  'token' => $token->plainTextToken,
]);

And done! Users of your application will now be authenticated using personal access tokens from Sanctum.