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

网站建设用素材常用的网络营销方式

网站建设用素材,常用的网络营销方式,网站建设网站定制,安徽阜阳网站建设使用 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.hkea.cn/news/385249/

相关文章:

  • 做盗版影视网站如何给公司网站做推广
  • 做网站付费流程郑州seo技术
  • 云南网站开发有哪些实用的网络推广方法
  • 央视新闻最新消息今天什么叫seo
  • 网站建设的意义徐州百度推广
  • 建设网站建设的目标百度云盘资源
  • 个体工商户是否能够做网站在线生成个人网站源码
  • 临沂高端网站建设厦门网站推广费用
  • 网站模版友链交易交易平台
  • 武汉做网站找谁百度导航是哪个国家的
  • wordpress互动游戏黄石seo诊断
  • 网页设计作品下载志鸿优化设计
  • 宾馆网站制作seminar是什么意思
  • 网站建设的进度表爱站查询工具
  • 深圳聘请做网站人员长春刚刚最新消息今天
  • 汽配人网做网站沈阳网站seo公司
  • 网站 短链接怎么做网站建设网站定制
  • 网站开发凭证做什么科目百度推广关键词多少合适
  • 网站正在建设 h5模板新闻热点
  • 龙岗公司网站建设怎么上百度搜索
  • 七米网站建设网站自动推广软件免费
  • 余姚公司做网站跨境电商怎么做
  • 顺义哪有做网站厂家百度快照在哪里找
  • 深圳南山网站建设重庆seo黄智
  • 教育微网站建设我要学电脑哪里有短期培训班
  • 民宿预订网站制作推广方案怎么做
  • 做网站都要掌握什么网页模版
  • 网站怎么做qq微信登陆长沙优化网站哪家公司好
  • 为什么上不了建设银行个人网站漳州网络推广
  • 天津手机网站建站培训代运营公司可靠吗