简体   繁体   English

验证部署在nodejs上的angular应用的jwt令牌的更好方法

[英]better way to verify jwt token for angular app deployed on nodejs

I have created a server using the express framework. 我已经使用express框架创建了服务器。 I have implemented the JWT. 我已经实现了JWT。 I have created an angular app then copied to the public folder. 我创建了一个有角度的应用程序,然后将其复制到公用文件夹。 Then used 然后用

app.use(express.static(__dirname + "/public"));

to make this public. 公开。 Now I want to authenticate my angular routes. 现在,我想验证我的角度路线。 Now there could be a call for the URL that will be URL of angular routing like localhost:7000/a , localhost:7000/b and so on. 现在可以调用该URL,该URL将是角度路由的URL,例如localhost:7000/alocalhost:7000/b等。 Additionally, there will be calls for the actual files like CSS, images or other files. 此外,还会调用诸如CSS,图像或其他文件之类的实际文件。

So I have used a middleware to intercept all the server calls. 因此,我使用了中间件来拦截所有服务器调用。

app.use((req, res, next) => {
   let pwt = req.cookies ? req.cookies.pwt : null;
   jwt.verify(pwt, process.env.SECRET_KEY, (err, decoded) => {
       if (decoded) {
           res.sendFile(path.join(__dirname, 'public', 'index.html'));
       } else {
           let callbackUrl = encodeURIComponent("http://" + req.headers.host + req.originalUrl);
           res.redirect(process.env.AUTH_SERVER + "/auth?_r=" + callbackUrl);
        }
   });
});

I am checking the jwt token and return the index.html file for each request. 我正在检查jwt令牌,并为每个请求返回index.html文件。 when there is call for image or any other CSS files it returns the index.html file. 当调用图像或任何其他CSS文件时,它将返回index.html文件。

One way is to make an array of Angular routing URLs and serve the index.html file only if req.originalUrl is from that list. 一种方法是创建一个Angular路由URL数组,并仅当req.originalUrl来自该列表时才提供index.html文件。 But this is not the good approach, as the server should not have the knowledge of app routing. 但这不是一个好的方法,因为服务器不应该了解应用程序路由。 Is there any way to solve this problem? 有什么办法解决这个问题?

我认为,做到这一点的最佳方法是在构建SPA时以角度方式实现路由并将其保护在那里,但是使用快速中间件,只需从角度应用程序中保护API请求即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM