背景:Cocos Creator导出html页面需要使用第三方登录做访问限制保护。
解决思路:不能让用户直接访问到index.html,使用nest-js写一个登录服务做跳转拦截,转发index.html。
公网服务器限制访问端口,仅开放80端口,用户访问公网域名 aaa.bbb.com ,使用nginx做代理转发:
server {
listen 80;
location / {
proxy_pass http://localhost:1234/;# 1234为nest-js登录服务监听端口
}
}
nest-js使用中间件做访问拦截,检测用户是否登录:
consumer.apply(LoginMiddleware).forRoutes('*');
检测条件为判断cookies里是否保存了登录的token(这个变量可以自定义,不一定要叫token):
req.cookies.token
cookies的提取使用 cookie-parser 中间件提取cookie数据:
import * as cookieParser from 'cookie-parser';
...
app.use(cookieParser());
如果token检测不通过,则重定向到第三方登录页面,同时挂起:
res.redirect(`https://${登录网址}`);
如果token检测通过,则调用 next();
通过路由 '/' 获取index.html数据并返回:
import { Injectable, HttpService } from '@nestjs/common';
...
@Controller('/')
...
constructor(private httpService: HttpService) { }
@Get()
async getHtml() {
const result = await this.httpService.get(`http://localhost:${index所在端口}`);
const r = await result.toPromise();
return r.data;
}
index.html服务使用nginx做代理转发
server {
listen 5678;//
server_name http://localhost;
location / {
root /xxx/xxx/;# index.html所在本地目录
}
}
最后index.html需要访问cocos creator导出的静态资源:
app.useStaticAssets(`${cocos creator导出的静态资源路径}`);
参考: