2

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 ?

Biswa
  • 479
  • 7
  • 11

2 Answers2

2

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')
    // ...
}
crbast
  • 2,192
  • 1
  • 11
  • 21
  • This is not working. When I add a new guard named admin it gives an error to add in guard list. You can try this on new web scaffolding of Adonis 5. Got error on driver i.e lucid or basic – Biswa Jun 07 '21 at 18:39
  • Did you install lucid provider? Can you share the full error? – crbast Jun 10 '21 at 05:32
  • Yes I have installed Lucid. I am giving you full error. Your answer is for API scaffolding. I am using web scaffolding. You can try new version of web scaffolding. – Biswa Jun 13 '21 at 10:37
  • One more thing Do I need to use custom User provider to achieve this ?? – Biswa Jun 13 '21 at 10:49
  • Doesn't work, seems like typescript screams at you – Santiago Jul 15 '21 at 20:36
0

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'>,
    }
    .....
  }
  .....
hahnavi
  • 9
  • 1
  • 3
  • Can you provide the detailed process of how a seperate admin panel can be setup in adonis 5 using AdminUser Model ? – Biswa Apr 14 '22 at 16:07