Protect non-api route (res.render) with express-jwt token in Node.js

First of all, I have read all the guides for securing REST API routes with jwt (express-jwt and jsonwebtoken) and it works great for this purpose.

This works great:

app.use('/api', postApiRoute);

      

And this works too, I mean it validates the token when I use it to show the web page with angular HTTP requests, but when you add expressJwt({secret: secret.secretToken})

you can't just access localhost:3000/api/post

more. The problem is expressJwt({secret: secret.secretToken})

here.

app.use('/api', expressJwt({secret: secret.secretToken}));
app.use('/api', userApiRoute);

      

I really need to protect the non-json route, but the html / text request with jwt, like this:

app.get('/admin*', expressJwt({secret: secret.secretToken}), function(req, res){
    res.render('index', {
        //user: req.session.user, <- not sure how to do the equivalent, to extract the user json-object from the express-jwt token?
        js: js.renderTags(),
        css: css.renderTags()
    });
});

      

.. without having to make http requests in angular / js, but using the 'render' expression function.

I need to do this since my application has 2 routed views of the primary server, so 1 is where the admin scripts are loaded and 1 is where the frontend resources (themes) are loaded.

I can't get jwt / tokens to work with server-rendered views, only json api requests.

The error I receive is "UnauthorizedError: no authorization header"

Couldn't find any information about (server-handled views, protected with jwt, only serveri api requests and angular client-side / ajax http requests) so I hope my question is clear and that I don't need to go back to use of sessions.

+3


source to share


1 answer


Not sure if I understood correctly, but if you are talking about html input routes (i.e. loaded directly by the browser, not with an angular app), then you simply have no way of instructing the browser on how to set the authorization header ( no, without introducing any other redirect based stream).



0


source







All Articles