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 ?
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 ?
You can configure multiple authentication by adding new auth in your config/auth.ts
in guards
section.
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')
}
}
}
}
public async myCustomControllerFunction ({ auth, response }: HttpContextContract, next: () => Promise<void>) {
const clientAuth = auth.use('api_clients')
// ...
}
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'>,
}
.....
}
.....