How to get separated auth for admin and user models in Adonis JS

Viewed 1260

Is it possible to have separated Auth for different models in Adonis Js?

I have two different table for admins and users and want to have separated Auth.

How can I setup this in adonis js ?

2 Answers

You can configure multiple authentication by adding new auth in your config/auth.ts in guards section.

Example

config/auth.ts :

const authConfig: AuthConfig = {
  guard: 'api_users',
  guards: {
    // User API token authentication
    api_users: {
      driver: 'oat',
      tokenProvider: {
        driver: 'database',
        table: 'user_api_tokens' // API token table - don't forget to create migration
      },
      provider: {
        driver: 'lucid',
        identifierKey: 'id',
        uids: ['name'],
        model: () => import('App/Models/User')
      }
    },
    // Client API token authentication
    api_clients: {
      driver: 'oat',
      tokenProvider: {
        driver: 'database',
        table: 'client_api_tokens' // API token table - don't forget to create migration
      },
      provider: {
        driver: 'lucid',
        identifierKey: 'id',
        uids: ['email'],
        model: () => import('App/Models/Client')
      }
    }
  }
}

Switch authentication :

public async myCustomControllerFunction ({ auth, response }: HttpContextContract, next: () => Promise<void>) {
    const clientAuth = auth.use('api_clients')
    // ...
}
Related