2

是否可以在 Adonis Js 中为不同模型分离 Auth

我有两个不同的管理员和用户表,并且想要分开 Auth

如何在 adonis js 中进行设置?

4

2 回答 2

1

您可以通过在config/auth.tsinguards部分中添加新的身份验证来配置多重身份验证。

例子

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')
    // ...
}
于 2021-06-06T17:59:22.540 回答
1

您可以通过在 contracts/auth.ts 文件中注册来创建新的守卫或提供者,以通知 TypeScript 静态编译器。

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

例子:

  .....
  interface GuardsList {
    .....
    apiUsers: {
      implementation: OATGuardContract<'user', 'apiUsers'>,
      config: OATGuardConfig<'user'>,
    }
    .....
  }
  .....
于 2021-08-01T06:03:28.960 回答