You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS JWT认证问题:无法用email登录,仅识别username字段

NestJS JWT认证:需传入username才能登录,期望改用email字段

刚接触NestJS一天,遇到一个问题:使用JWT认证时,前端必须传入格式为{"username":"test@gmail.com", "password": "password123"}的JSON数据才能完成登录,但我希望改用{"email":"test@gmail.com", "password": "password123"}作为登录参数,且我的代码库中从未定义或提及过username字段。

我尝试过修改所有相关参数名称、用户Schema、添加DTO,搜索自定义参数名或覆盖默认值的方法,查找是否存在默认username参数的来源,但均未解决问题。

相关代码

users.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);
  }
}

users.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();
  }
}

auth.controller.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);
  }
}

内容的提问来源于stack exchange,提问作者networkdavit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:20:35