Feathers Js Restrict Access To Page on Server Side

你离开我真会死。 提交于 2019-12-04 10:21:31

To do restriction in a page-load scenario, you'll need to first make sure that the token is in a cookie. Check out the feathers-authentication documentation for how to enable cookies. But it's super important that you are careful to not expose yourself to CSRF attacks through the cookie.

With the current version of the feathers-authentication plugin, you'll have to set this up manually. You'll need to read the token out of the cookie for the rendering middleware to use:

const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use('/payment-info.html', function(req, res, next) {
  let token = req.cookies['feathers-jwt'];
  if (token) {
    // Get the JWT secret to verify the token.
    let secret = app.get('auth').token.secret;
    jwt.verify(token, secret, function(err, decoded) {
      if (err) {
        return res.status(401).send('You are not authorized to view that page.');
      }
      return next();
    });
  } else {
    return res.status(401).send('You are not authorized to view that page.');
  }
});

It's important that you never allow any services to directly use the token from the cookie. It's fine for the rendering middleware to pull the token and use it to make service requests as though it is just another client, but you would never want to pull it from the cookie and colocate it on the req.feathers object for authorization inside of a service. That's how you open your API up to CSRF attacks.

Also, if you're enabling CORS at all, you'll more than likely want to make sure that CORS are disabled for the rendering middleware. Only enable CORS just before your Feathers services.

Another drawback of feathers-authentication@0.7.x is that the cookie expiration is not matched up with the token's expiration. You'll need to manually set the cookie's maxAge expiration to match how long you want your tokens to be valid, as explained in the docs.

feathers-authentication@1.x.x (which is currently in pre-release), will include better support for server side rendering, so you won't have to wire it up yourself. It will also take care of making the cookie expire with the token.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!