For our example, we’ll create a very basic API endpoint that returns a secret code if user performs a GET request with a valid JWT in the request header. The endpoint lives in server/routes/index.js and looks like this:
var express = require('express'); var router = express.Router(); var passport = require('passport'); router.get('/protected', function (req, res, next) { passport.authenticate('jwt', function (err, user, info) { if (err) { // internal server error occurred return next(err); } if (!user) { // no JWT or user found return res.status(401).json({ error: 'Invalid credentials.' }); } if (user) { // authentication was successful! send user the secret code. return res .status(200) .json({ secret: '123' }); } })(req, res, next); }); module.exports = router; When a user accesses /protected, we call passport.authenticate using the JWT strategy we defined in the previous step. The passport-jwt library then checks the request headers to see if a JWT was sent with the request. If no JWT is found, or if the JWT is invalid for any reason, we return a 401 UNAUTHORIZED response with a description of the error in the body of the response. If authentication succeeds, we respond with the secret code that the user requested.
We can test our endpoint using cURL (make sure your Node server is running!):
$ curl http://localhost:3000/protected {"error":"Invalid credentials."} Since we have not send any credentials with the request, this response is expected.
This code sample shows the gist of protecting API endpoints with the JWT strategy. For more complex real-world use cases, you’d likely want to define some sort of utility function that would make this bit of code more portable and reusable. This authentication callback can then be included in any route definitions that require this protection, avoiding the need to copy and paste the same conditional checks in every route.
Let’s work on our registration and login endpoints next.