Hey everyone. So a few days ago I made this threadhttps://www.reddit.com/r/node/comments/ce8ki0/if_you_sign_a_jwt_with_the_exact_same_password_on/Asking about basically modularizing an Express back-end into several different servers that work together. You guys pointed out to me that a fundamental aspect of this architecture is having one server handle the signing/checking of JWT keys and having other servers communicate with this Auth server via public keys. This way, only one of the servers is dealing with the secret key - the Auth server.I've been trying to figure this out on my own by looking at older API's I made and thinking of how I would build them with this architecture. The code below is from an Express/Mongoose API I made last year that is fully centralized in one server.My login route logic:// Login User exports.login = (req, res) => { User.findOne({ username: req.body.username }).exec() .then((user) => { if (bcrypt.compareSync(req.body.password, user.password) === true) { const token = jwt.sign({ username: user.username, id: user._id }, process.env.JWT_KEY, { expiresIn: '12h' }); return res.json({ message: 'Login successful.', token, username: user.username, id: user._id, }); } return res.status(400).json({ message: 'Login failed.' }); }) .catch(() => res.status(500).json({ message: 'Login failed.' })); }; My Auth middleware that all protected routes go through before executing the actual logic:const jwt = require('jsonwebtoken'); module.exports = (req, res, next) => { try { const token = req.headers.authorization.split(' ')[1]; const decoded = jwt.verify(token, process.env.JWT_KEY); req.tokenData = decoded; next(); } catch (err) { res.json('Authentication Failed.'); } }; So basically, you get a JWT when you sign in. That JWT is checked when you try to do something that is behind the Auth middleware.Now, let's re-purpose it for a multi-server architecture.If I'm understanding correctly... the Auth server would comprise of these two functionalities that I have posted above. Handing out the JWT for users logging in, and then checking the legitimacy of the token for protected routes.However, when I think about it in my mind, I'm just thinking of making API calls from one API to another. So my logic for a protected route doesn't go through a Auth middleware on the same server, but instead makes a fetch request to the separate Auth server. I can't figure out where "public keys" that everyone in that thread was talking about fits in here. Can someone enlighten me?I'm not necessarily asking for actual code samples (although if you have some at hand, feel free to share them) but a logic walk-through in plain English. Either of those would be helpful.Thank you!
Submitted July 20, 2019 at 07:11PM by ClassicPurist
No comments:
Post a Comment