简体   繁体   中英

Authenticate requests in node.js against Wordpress

I have a Wordpress site and a node.js application which together form the web application I'm building. I'm using Node because of socket.io and Wordpress for a lot of other reasons. Either way I cant drop wordpress or node

The problem I face is making sure a user who is logged in via wordpress is a valid user when making requests to the Node server.

Should I push session info to the node server during the wordpress auth process and have it maintain it's own sessions? And then on subsequent requests to the Node server just use that?

I'm struggling to get my head around this and would appreciate any help.

Take a look at passportjs which is an authentication module for node.js which provides different authentication strategies (as of today more than 140). Fortunately there is a OAuth 2 stategy for authenticating against wordpress. The github page of this strategy is located here .

Both, passport and the passport-wordpress, can be installed via npm package manager. Afterwards, you could authenticate every request for example with passport.authorize() route-middleware method if your node application is an express.js application. From the docs of passport-wordpress:

Define the strategy.

passport.use(new WordpressStrategy({
    clientID: CLIENT_ID,
    clientSecret: CLIENT_SECRET
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({ WordpressId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

Using the strategy via passport.authorize in your routes (example for expressjs):

app.get('/auth/wordpress',
  passport.authorize('wordpress'));

app.get('/auth/wordpress/callback', 
  passport.authorize('wordpress', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

If you're not using expressjs or don't want to use passportjs, please provide some more information how your wordpress installation and your node.js application is working together and what kind of frameworks you're using on the node.js side.

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