简体   繁体   English

使用db进行Loopback 4身份验证

[英]Loopback 4 authentication using a db

I am trying to implement authorization to my loopback4 project using this tutorial https://github.com/strongloop/loopback-next/blob/master/packages/authentication/README.md Now on the provider part on the file called auth-strategy.provider, on the verify method, I want to verify the username with a mongoDB. 我正在尝试使用本教程https://github.com/strongloop/loopback-next/blob/master/packages/authentication/README.md对我的loopback4项目实现授权现在在名为auth-strategy的文件的提供者部分.provider,在验证方法上,我想用mongoDB验证用户名。 I already have a repository and database access on the project. 我已经在项目上拥有存储库和数据库访问权限。 My question is how do I access the database from this part of the code? 我的问题是如何从代码的这一部分访问数据库?

You can inject your repository in the constructor of your provider and then compare the password to check if it's ok like this: 您可以在提供者的构造函数中注入您的存储库,然后比较密码以检查它是否正常如下:

  import {repository} from '@loopback/repository';

  export class MyAuthStrategyProvider implements Provider<Strategy | undefined> {
  constructor(
    @inject(AuthenticationBindings.METADATA)
    private metadata: AuthenticationMetadata,
    @repository(UserRepository) protected userRepository: UserRepository,
  ) {}

  [...]

  verify(
    username: string,
    password: string,
    cb: (err: Error | null, user?: UserProfile | false) => void,
  ) {
    let user = await this.userRepository.findOne({where: {username: username}});
    if(!user || user.password !== password)
         return cb(null, false);
    cb(null, user);
  }
}

This code is just a sample, in general the password should be hashed in the database. 此代码只是一个示例,通常密码应该在数据库中进行哈希处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM