视频演示:
www.bilibili.com/video/BV1BT…
一起来完成以下步骤:
- 引用之前的工程代码
- 创建员工信息interface和员工数组array
- 生成token
- 校验token是否正确
- 运行命令: deno run --allow-net --allow-read main.ts
import { Context } from "https://deno.land/x/oak/mod.ts";
import { key } from "../middlewares/key.ts";
import { makeJwt, setExpiration, Jose, Payload } from "https://deno.land/x/djwt/create.ts"
import employees from "../models/employees.ts";
const { cwd } = Deno;
const header: Jose = {
alg: "HS256",
typ: "JWT",
}
#middlewares/authMiddleware.ts
import { Context } from "https://deno.land/x/oak/mod.ts";
import { validateJwt } from "https://deno.land/x/djwt/validate.ts"
import { key } from "./key.ts";
const authMiddleware = async (ctx: Context, next: any) => {
const headers: Headers = await ctx.request.headers;
const authorization = headers.get('Authorization')
if (!authorization || !authorization.split(' ')[1] ) {
ctx.response.status = 401;
return;
}
const jwt = authorization.split(' ')[1];
const isValidateJwt = await validateJwt(jwt, key);
if (isValidateJwt.isValid) {
await next();
return;
}
ctx.response.status = 401;
ctx.response.body = { message: 'Invalid jwt token' };
}
export default authMiddleware;
#models/employee.ts
export interface Employee{
id: string,
username: string,
password: string
}
const employees: Array<Employee> =[
{
id: "1",
username: "michael",
password: "123456"
},
{
id: "2",
username: "alex",
password: "654321"
}
]
export default employees;
#routers/router.ts
import { Router } from "https://deno.land/x/oak/mod.ts";
import Controller from "../controllers/Controller.ts";
import authMiddleware from "../middlewares/authMiddleware.ts";
const router = new Router();
router.get("/",Controller.hello);
router.get("/guest",Controller.guest);
router.post("/token",Controller.token);
router.get("/admin",authMiddleware,Controller.admin);
export default router;
#main.ts
import { Application } from "https://deno.land/x/oak/mod.ts"
import {viewEngine,engineFactory,adapterFactory} from "https://deno.land/x/view_engine/mod.ts";
import router from "./routers/router.ts";
const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();
const app = new Application();
app.use(viewEngine(oakAdapter,ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server Port 8000");
await app.listen({port: 8000 })