当前位置: 首页 > news >正文

哈尔滨网站建设有哪些网站的备案号查询

哈尔滨网站建设有哪些,网站的备案号查询,优质院校 建设网站,seo网站整站优化使用 Nest.js 开发项目时,处理身份验证和授权是常见的需求,可以采用以下架构和实现方式。 架构 用户认证模块 (Auth Module): 服务 (Service): 处理用户登录逻辑,生成 JWT(JSON Web Token),以及验证 token…

使用 Nest.js 开发项目时,处理身份验证和授权是常见的需求,可以采用以下架构和实现方式。

架构

  1. 用户认证模块 (Auth Module):

    • 服务 (Service): 处理用户登录逻辑,生成 JWT(JSON Web Token),以及验证 token。
    • 控制器 (Controller): 提供登录接口,处理来自客户端的请求。
    • 中间件/守卫 (Guards): 在需要保护的路由中,验证请求头中的 token,决定是否放行。
  2. JWT 模块:

    • 利用 Nest.js 提供的 JWT 模块来简化 token 的生成与验证。
  3. 数据库模块:

    • 用于存储和查询用户信息,可能使用 TypeORM 或 Mongoose 等库来操作数据库。

实现步骤

1. 安装所需的依赖

在项目中安装以下依赖:

npm install @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt
2. 创建 Auth Module

生成 Auth 模块:

nest g module auth
nest g controller auth
nest g service auth
3. 实现用户登录逻辑

auth.service.ts 中实现用户登录和 token 生成逻辑:

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service'; // 假设你有一个用户服务
import { User } from '../user/user.entity'; // 假设你有一个用户实体
import * as bcrypt from 'bcrypt';@Injectable()
export class AuthService {constructor(private userService: UserService,private jwtService: JwtService,) {}async login(username: string, password: string): Promise<string> {const user: User = await this.userService.findByUsername(username);if (user && await bcrypt.compare(password, user.password)) {const payload = { username: user.username, sub: user.id };return this.jwtService.sign(payload);}throw new Error('Invalid credentials');}
}
4. 创建登录接口

auth.controller.ts 中添加登录接口:

import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';@Controller('auth')
export class AuthController {constructor(private authService: AuthService) {}@Post('login')async login(@Body() loginDto: { username: string; password: string }) {return this.authService.login(loginDto.username, loginDto.password);}
}
5. 设置 JWT 模块

auth.module.ts 中配置 JWT 模块:

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service'; // 引入用户服务@Module({imports: [JwtModule.register({secret: 'your_secret_key', // 应该放在环境变量中signOptions: { expiresIn: '60s' }, // token 过期时间}),],controllers: [AuthController],providers: [AuthService, UserService],
})
export class AuthModule {}
6. 创建 JWT 校验守卫

创建一个守卫来验证 token,在 auth.guard.ts 中实现:

import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {handleRequest(err, user) {if (err || !user) {throw new UnauthorizedException();}return user;}
}
7. 设置 JWT 策略

auth.strategy.ts 中定义 JWT 策略:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { UserService } from '../user/user.service'; // 引入用户服务
import { JwtPayload } from './jwt.payload'; // 定义 payload 接口@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {constructor(private userService: UserService) {super({jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),ignoreExpiration: false,secretOrKey: 'your_secret_key', // 应该放在环境变量中});}async validate(payload: JwtPayload) {return this.userService.findById(payload.sub); // 根据 payload.sub 查找用户}
}
8. 保护路由

在需要保护的控制器中使用守卫:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './auth.guard';@Controller('protected')
export class ProtectedController {@UseGuards(JwtAuthGuard)@Get()getProtectedResource() {return 'This is a protected resource';}
}

总结

通过以上步骤,可以实现一个简单的用户登录和 JWT 身份验证系统。用户登录时会生成 token,而在需要保护的接口中,通过中间件校验 token 的有效性,以决定是否放行请求。建议把 secret key 存放在环境变量中,以增强安全性。

http://www.yayakq.cn/news/674198/

相关文章:

  • 个人网站 如何做推广wap浏览器
  • 建设一个官方网站多少钱网站套站
  • 网站怎么推广效果最好潍城区建设局网站
  • 网站制作多少钱一个做网站那个程序好
  • 郑州树标网站建设用flask做的网站
  • 阿里网站官网入口wordpress标题连接符
  • 网站查询ip地址购物网站开发教程中文版
  • 修改网站默认首页朋友圈广告推广文字
  • wordpress显示网站运行网站做百度推广有没有效果
  • 广西临桂建设局网站要学做网站
  • 企业网站优化技巧WordPress信息收集
  • 做政协网站的目的是什么wordpress 网站加载过慢6
  • flash网站设计实例wordpress 子菜单顺序
  • 网站找人做seo然后网站搜不到了wordpress调用目录
  • 家乡网站设计目的wordpress如何设置邮箱验证码
  • 镇网站制作价格做网站需注意什么
  • 阿里云个人网站备案做网站商铺模板
  • 顺德网站建设公司咨询wordpress博客简洁主题
  • 广州 企业网站建设ios软件开发需要学什么
  • 做三年网站需要多少钱做网站的怎么赚钱
  • 江西省住房和城乡建设厅的网站怎么制作自己的小网站
  • 广西网站建设证件查询信誉好的做网站公司
  • 网站建设空格怎么打电子商务网站建设与管理实验
  • 天动力网站开发网站建设 开发
  • 景德镇网站建设哪家好二维码图片生成器在线制作
  • 网站开发电子书欧洲c2c平台
  • 好的摄影网站移动宽带可以在网上续费吗
  • 网站接单园区网站建设调研报告
  • 下载类网站 前置备案临安市建设局网站
  • 旅游建设网站目的及功能定位珠海市外贸网站建设公司