简体   繁体   中英

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

I have created a server using the express framework. I have implemented the 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. Additionally, there will be calls for the actual files like CSS, images or other files.

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. when there is call for image or any other CSS files it returns the index.html file.

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. 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请求即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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