'Laravel Passport Client Credentials Grant Tokens with Nuxt

I have a Laravel Api with Passport, I put the Client Credentials Grant Tokens and everything works fine from Laravel Side, now I can't find the best way to consume the Api from Nuxt SSR.

I already implement the API in my Nuxt Pages and Components, but, now I do not how to manage the token, I already use nuxtServerInit and get the token, but, I can't put if setToken in Axios Plugin, I use the store, but in the Axios plugin comes empty, then I use a cookie, the first time is set the token, but when the token expire I get the 401 status, now, I do not how to refresh the token without refresh the page and verify in any request of axios and refreshing. I try the axios interceptors but not working.

I am trying to use @nuxt/auth but can't find the best approach. I use private runtime config in nuxt to manage the client_id, client_secret to not be exposed to the client.

Anybody can help?



Solution 1:[1]

I was also facing the same issue and this worked for me. This for client_credentials type grant using laravel passport. Use the following auth values

auth: {
strategies: {
  local: {
    token: {
      property: 'access_token',
      global: true,
      type:'Bearer'
    },
    endpoints: {
      login: {
        url: '/oauth/token',
        method: 'post',
        propertyName:'access_token',
        data: {
          grant_type: 'client_credentials',
          client_id: process.env.PASSPORT_CLIENT_ID,
          client_secret: process.env.PASSPORT_CLIENT_SECRET,
        }
      },
      logout: {
        url: '/oauth/tokens/',
        method:'delete'
      },
      user: {
        url: '/api/user',
        method: 'get',
        propertyName:false
      }
    }
  }
}

}

Then inside your application logic you can use

this.$auth.loginWith('local')
   .then((res)=>{
     console.log(res)
   })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deepak Sharma