【问题标题】:Nest JS user authentication issue with parameter name带有参数名称的 Nest JS 用户身份验证问题
【发布时间】:2022-11-24 20:33:36
【问题描述】:

我刚刚学习 nestjs 大约一天,我遇到了这个奇怪的错误,可能与我不了解我在做什么而匆忙完成项目有关,所以请多多包涵。我的主要问题是,在使用 JWT 身份验证时,来自正文的 JSON 是“用户名”,我无法更改它。我想使用 {"email":"test@gmail.com", "password": "password123"} 登录,但它只接受 {"username":"test@gmail.com", "password": “密码123”}。我的代码库中的任何地方都没有定义或提及“用户名”一词

用户.controller.ts

import { Controller, Get, Post, Body, Param, UseGuards } from '@nestjs/common';
import { UsersService} from './users.service';
import { CreateUserDto} from './dto/create-user.dto';
import { AuthGuard} from '@nestjs/passport';

@Controller('/users')
export class UsersController {
  // constructor(private readonly usersService: UsersService) {}

  constructor(private readonly userService: UsersService) {}

  @UseGuards(AuthGuard('jwt'))
  @Get('username')
  getUserByEmail(@Param() param) {
    return this.userService.getUserByEmail(param.email);
  }
  @Post('register')
  registerUser(@Body() createUserDto: CreateUserDto) {
    return this.userService.registerUser(createUserDto);
  }
}

用户.service.ts

import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { HashService } from './hash.service';
import { User, UserDocument} from '../schemas/user.schema'

@Injectable()
export class UsersService {

  constructor(@InjectModel(User.name) private userModel: Model < UserDocument > , private hashService: HashService) {}

  async getUserByEmail(email: string) {
    return this.userModel.findOne({
        email
      })
      .exec();
  }

  async registerUser(createUserDto: CreateUserDto) {
    // validate DTO

    const createUser = new this.userModel(createUserDto);
    // check if user exists
    const user = await this.getUserByEmail(createUser.email);
    if (user) {
      throw new BadRequestException();
    }
    // Hash Password
    createUser.password = await this.hashService.hashPassword(createUser.password);

    return createUser.save();
  }
}

授权控制器.ts

import { AuthService} from './auth.service';
import { Controller, Request, UseGuards, Post} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}
  @UseGuards(AuthGuard('local'))
  @Post(`/login`)
  async login(@Request() req) {
    console.log(req.user, "here")
    return this.authService.login(req.user);
  }
}

这里是源码https://github.com/networkdavit/pillicam_test 非常感谢任何帮助或建议!

我尝试更改所有参数名称、用户模式、添加 DTO,我用谷歌搜索如何添加自定义参数名称或覆盖它,试图查找“默认用户名参数”是否确实存在。到目前为止,没有什么对我有用

【问题讨论】:

    标签: jwt nestjs


    【解决方案1】:

    它在您的代码中的 username 中。 https://github.com/networkdavit/pillicam_test/blob/main/src/users/entities/user.entity.ts#:~:text=class%20User%20%7B-,username%3A%20string%3B,-password%3A%20string

    你可以改变它。

    或者你可以参考this nest.js中JWT实现的文章

    【讨论】:

    • 是的,关于那个,我只是在发送代码之前更改了它,它不再是用户名,但仍然不起作用,
    • 你看过我提到的那篇文章了吗? blog.logrocket.com/how-to-implement-jwt-authentication-nestjs/… 您可以用另一种方式定义用户架构。 @networkdavit
    • 是的,我做到了,仍然没有运气,但我想我会继续努力解开这个谜团
    【解决方案2】:

    以防万一有人遇到这个问题,我找到了解决方案。 我所要做的就是将它添加到构造函数中的 local.strategy.ts 文件中

    super({
      usernameField: 'email',
      passwordField: 'password'
    });
    

    默认需要用户名和密码,所以必须手动修改

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2017-02-08
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多