We have successfully signed a token and returned it to the client when the credentials match what we have stored in the database. But that is only half of the story. We should verify this token each time the client makes a request with it, to access all protected routes guarded by the server-side middleware.
So, let's create the middleware and the protected route in the following steps:
-
Create a middleware file in the /middlewares/ directory inside the /src/ directory with the following code:
// src/middlewares/authenticate.js
import jwt from 'jsonwebtoken'
import config from 'config'
export default async (ctx, next) => {
if (!ctx.headers.authorization) {
ctx.throw(401, 'Protected resource, use Authorization header
to get access')
}
const token = ctx.headers.authorization.split(' ')[1]
try {
ctx.state.jwtPayload = jwt.verify(token, config.JWT_SECRET)
} catch (err)...