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

1.9k Views Asked by At

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

There are 2 best solutions below

5
On

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')
    // ...
}
1
On

You can create new guards or providers by register them inside the contracts/auth.ts file to inform the TypeScript static compiler.

https://docs.adonisjs.com/guides/auth/introduction#configuring-new-guardsproviders

Example:

  .....
  interface GuardsList {
    .....
    apiUsers: {
      implementation: OATGuardContract<'user', 'apiUsers'>,
      config: OATGuardConfig<'user'>,
    }
    .....
  }
  .....