• 基于typescript+express实现一个简单的接口权限验证


     package.json

    1. "scripts": {
    2. "start": "nodemon src/main.ts",
    3. "start:a": "nodemon src/a.ts",
    4. "build": "tsc",
    5. "build:dev": "tsc src/main.ts"
    6. },

    express服务器文件

    1. import * as express from 'express';
    2. import { Request, Response, NextFunction } from 'express'
    3. import * as jwt from 'jsonwebtoken';
    4. const app = express();
    5. const secretKey = 'sean';
    6. app.use(express.static("static"))
    7. interface AuthenticatedRequest extends Request {
    8. user?: any;
    9. }
    10. // 登录接口
    11. app.post('/login', (req: AuthenticatedRequest , res: Response) => {
    12. // 假设登录验证成功,生成Token
    13. const token = jwt.sign({ username: 'admin' }, secretKey, { expiresIn: '1h' });
    14. res.json({ token });
    15. });
    16. // 验证Token的中间件
    17. const authenticateToken = (req: AuthenticatedRequest , res: Response, next: NextFunction) => {
    18. const authHeader = req.headers['authorization'];
    19. console.log("authHeader:",authHeader)
    20. // const token = authHeader && authHeader.split(' ')[1];
    21. const token = authHeader;
    22. console.log("token:",token)
    23. if (token == null) {
    24. return res.sendStatus(401);
    25. }
    26. jwt.verify(token, secretKey, (err: any, user: any) => {
    27. if (err) {
    28. console.log("verify-err",err)
    29. return res.sendStatus(403);
    30. }
    31. req.user = user;
    32. next();
    33. });
    34. };
    35. // 需要验证Token的接口
    36. app.get('/protected', authenticateToken, (req: AuthenticatedRequest, res: Response) => {
    37. console.log("req",req)
    38. res.json({ message: 'Protected route', user: req.user });
    39. });
    40. app.get('/list', authenticateToken, (req: AuthenticatedRequest, res: Response) => {
    41. console.log("req",req)
    42. res.json({ data: [] });
    43. });
    44. app.get("/static",(req,res)=>{
    45. res.sendFile("index.html",{root:"./"})
    46. })
    47. // 启动服务器
    48. app.listen(4000, () => {
    49. console.log('Server is running on port 4000');
    50. });

    在根目录新建一个index.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body>
    9. <div id="app">
    10. <form >
    11. <div>
    12. <span>用户名:</span>
    13. <input id="user" type="text" placeholder="please input username">
    14. </div>
    15. <div>
    16. <span>密码:</span>
    17. <input id="password" type="password" placeholder="please input username">
    18. </div>
    19. <div>
    20. <button id="btn">提交</button>
    21. </div>
    22. </form>
    23. <div >
    24. <button id="send">send</button>
    25. </div>
    26. <div >
    27. <button id="listBtn">获取list</button>
    28. </div>
    29. </div>
    30. </body>
    31. </html>
    32. <script>
    33. let user=document.getElementById("user")
    34. let password=document.getElementById("password")
    35. let btn=document.getElementById("btn")
    36. let sendBtn=document.getElementById("send")
    37. let listBtn=document.getElementById("listBtn")
    38. const submit=(e)=>{
    39. e.preventDefault()
    40. let data={
    41. username:user.value,
    42. password:password.value
    43. }
    44. fetch("http://localhost:4000/login",{method:"post",body:JSON.stringify(data)}).then(res=>{
    45. res.json().then(res=>{
    46. console.log("response",res)
    47. let token=res.token;
    48. sessionStorage.setItem("authorization",token)
    49. })
    50. })
    51. console.log("data",data)
    52. }
    53. const request=()=>{
    54. fetch("http://localhost:4000/protected",{
    55. method:"get",
    56. headers:{
    57. "authorization":sessionStorage.getItem("authorization")
    58. }
    59. }).then(res=>{
    60. res.json().then(response=>{
    61. console.log("pretect--response",response)
    62. })
    63. })
    64. }
    65. const requestList=()=>{
    66. fetch("http://localhost:4000/list",{
    67. method:"get",
    68. headers:{
    69. "authorization":sessionStorage.getItem("authorization")
    70. }
    71. }).then(res=>{
    72. res.json().then(response=>{
    73. console.log("pretect--response",response)
    74. })
    75. })
    76. }
    77. btn.addEventListener("click",submit)
    78. sendBtn.addEventListener("click",request)
    79. listBtn.addEventListener("click",requestList)
    80. </script>

  • 相关阅读:
    Simple Factory Pattern 简单工厂模式简介与 C# 示例【创建型】【设计模式来了】
    支付宝沙箱支付
    【Servlet】1:踏入JavaWeb的第一把钥匙
    8.strtok函数
    打造一个开箱即用的超级丝滑的漂亮hexo博客网站
    LeetCode刷题复盘笔记—一文搞懂0 - 1背包之494. 目标和问题(动态规划系列第九篇)
    【FLink】Flink 任务 如何优雅的停止
    Java之常用类
    Stable Diffusion webui 源码调试(二)
    应急安全的“青岛模式”:如何打造更有韧性的城市?
  • 原文地址:https://blog.csdn.net/baidu_41601048/article/details/134000373