分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

Nestjs 身份验证

发布时间:2023-09-06 02:23责任编辑:林大明关键词:js

文档

yarn add @nestjs/passport passport passport-http-bearer @nestjs/jwt passport-jwt

auth.service.ts

import { JwtService } from '@nestjs/jwt';import { Injectable } from '@nestjs/common';// import { UsersService } from '../users/users.service';@Injectable()export class AuthService { ?constructor( ???// private readonly usersService: UsersService, ???private readonly jwtService: JwtService, ?) {} ?async signIn(): Promise<string> { ???// In the real-world app you shouldn't expose this method publicly ???// instead, return a token once you verify user credentials ???console.log(123) ???const user = { email: 'user@email.com' }; ???return this.jwtService.sign(user); ?} ?async validateUser(payload: any): Promise<any> { ???// return await this.usersService.findOneByEmail(payload.email); ???console.log(payload); ???return {}; ?}}

jwt.strategy.ts

import { ExtractJwt, Strategy } from 'passport-jwt';import { AuthService } from './auth.service';import { PassportStrategy } from '@nestjs/passport';import { Injectable, UnauthorizedException } from '@nestjs/common';@Injectable()export class JwtStrategy extends PassportStrategy(Strategy) { ?constructor(private readonly authService: AuthService) { ???super({ ?????jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ?????secretOrKey: 'secretKey', ???}); ?} ?async validate(payload: any) { ???const user = await this.authService.validateUser(payload); ???if (!user) { ?????throw new UnauthorizedException(); ???} ???return user; ?}}

app.module.ts

import { Module } from '@nestjs/common';import { AppController } from './app.controller';import { AppService } from './app.service';import { PassportModule } from '@nestjs/passport';import { JwtModule } from '@nestjs/jwt';import { AuthService } from './auth.service';import { JwtStrategy } from './jwt.strategy';@Module({ ?imports: [ ???PassportModule.register({ defaultStrategy: 'jwt' }), ???JwtModule.register({ ?????secretOrPrivateKey: 'secretKey', ?????signOptions: { ???????expiresIn: 3600, ?????}, ???}), ?], ?controllers: [AppController], ?providers: [AppService, AuthService, JwtStrategy],})export class AppModule {}

app.controller.ts

import { Get, Controller, UseGuards } from '@nestjs/common';import { AppService } from './app.service';import { Repository } from 'typeorm';import { AuthGuard } from '@nestjs/passport';import { AuthService } from './auth.service';@Controller()export class AppController { ?constructor( ???private readonly appService: AppService, ???private readonly authService: AuthService, ?) {} ?@Get('token') ?async createToken(): Promise<any> { ???return await this.authService.signIn(); ?} ?@Get('users') ?@UseGuards(AuthGuard()) ?users(): any { ???return [1]; ?}}

先获取token,在每次请求中发送token

λ curl localhost:5000/tokeneyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZW1haWwuY29tIiwiaWF0IjoxNTQzMDc0NDU1LCJleHAiOjE1NDMwNzgwNTV9.jtfgp3XxHT20h83k24Ukk0TgtYqGWZaCglUdtbVFmF4λ curl localhost:5000/users -H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZW1haWwuY29tIiwiaWF0IjoxNTQzMDc0NDU1LCJleHAiOjE1NDMwNzgwNTV9.jtfgp3XxHT20h83k24Ukk0Tgt YqGWZaCglUdtbVFmF4"[1]λ curl localhost:5000/users -H "authorization: Bearer 123"{"statusCode":401,"error":"Unauthorized"}

Nestjs 身份验证

原文地址:https://www.cnblogs.com/ajanuw/p/10014199.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved