Sunday, 14 May 2017

Use passport-jwt on server side rendered Express/React app

I have an universal NodeJS, Express, React/Redux app that uses react-router. It is rendered from server side on initial requests of the app and on client on subsequent requests that come from react-router.

My routes.js file:

<Route path="/" component={App}>
    <Route path="/main" component={Main}/>
    <Route path="/login" component={Login}/>
</Route>

I have a wildcard express route that matches this react-routes and sends the component markup back to the template:

import routes from '../routes';

app.get('*', (req, res) => {
    match(
        { routes, location: req.url },
        (err, redirectLocation, renderProps) => {
            let markup;
            if (renderProps) {
                markup = renderToString(
                    <Provider store={store}>
                        <RouterContext {...renderProps}/>
                    </Provider>
                );
            } else {
                markup = renderToString(<NotFoundPage/>);
                res.status(404);
            }

            return res.render('index', { markup });
        }
    );
});

Now I want to protect some of the routes intercepted by the wildcard route using passport-jwt, like the example:

app.get("/main", passport.authenticate('jwt', { session: false }), 
function(req, res){
    res.json("Success! You can not see this without a token");
});

How can I protect only a given route from routes.js ?



via André Teixeira

No comments:

Post a Comment