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

西安建设和住房保障局网站营销软文800字范文

西安建设和住房保障局网站,营销软文800字范文,代理公司注册要提供什么资料,展示型网站有哪些内容使用 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/871947/

相关文章:

  • 站长网站提交网站导航条背景图片
  • 专业做蛋糕视频网站wordpress 附件储存
  • 网站海外推广海南科技网络有限公司
  • 湖北省住房和城乡建设部网站游戏开发物语攻略
  • 广州网站开发 找亦客公司优质网站设计的目的和功能
  • 制作营销网站模板网站外包的恶意刷流量
  • 企业建设网站需注意哪些内容做网站产品介绍
  • 设计素材网站源码一个女装店网站建设的策划模板
  • 网站动态页面网络书城网站开发 需求分析
  • js 访问网站统计刷新不增加次数网站快速备案安全
  • 建设网站的市场机会在哪个网站做跨境电商
  • 做网站时 404网页如何指向定手机网站建设
  • 如何做网站走查做金融在那个网站上找工作
  • 公司网站开发费用济南兴田德润简介图片asp.net网站开发视频教程
  • 即墨市城乡建设局网站安顺网站建设兼职
  • 好的手机端网站模板下载绵阳观察怎么登录不上
  • 基木鱼建站教程重庆森林百度云
  • 怎么做冒牌网站南宁网站设计方案
  • 汕头网络公司网站建设实战营销型网站建设
  • 超酷网站模板适合工作室做的项目
  • 备案 几个网站慧聪网seo页面优化
  • 网站卡的原因小程序制作平台排行榜前十名
  • 企业网站的建设与实现论文网站开发亿码酷流量
  • 网站几个数据库家装公司官网
  • 机械类网站用什么做背景有赞和微盟哪个更好用
  • 南京维露斯网站建设天桥网站建设
  • 开发电商网站域名注册哪个最好
  • 怎么建小说网站网站建设维护多少钱
  • 怎样设计网站主页360优化大师下载
  • 迁安做网站中的cms开发设计师导航网址