With the model function for checking access tokens implemented, let’s create a middleware function to handle authenticating access tokens inside our application. Inside app.js, we will create a function named authenticateRequest()
that takes three arguments: req
, res
, next
.
Inside the function, we create a new variable named request
and set it to a new instance of OAuth2Server.Request()
, taking in the HTTP request, req
, as the argument.
let request = new OAuth2Server.Request(req);
We’ll create a new variable named response
and set it to a new instance of OAuth2Server.Response()
, passing in the HTTP response, res
.
let response = new OAuth2Server.response(res);
We then return .authenticate()
method, that is provided by the OAuth2Server
object, on oauth
, passing in response
and request
. The method returns a Promise
that resolves to the access token object returned from the .getAccessToken()
method we defined in model.js
. We’ll use a promise chain to handle the flow.
We use the .then()
method, and if the access token is valid, we can call the next()
function to call the next function. We’ll chain the .catch()
method to handle an error or if the access token is invalid. Inside .catch()
method, we can send a response back to the client using the .send()
method.
const authenticateRequest = (req, res, next) => { let request = new OAuth2Server.Request(req); let response = new OAuth2Server.Response(res); return oauth.authenticate(request, response) .then(()=>{ next(); }) .catch((err) => { res.send(err); }) }
Finally, we can add authenticateRequest
as a middleware function to a route to restrict access. Now the client must include the bearer token in the header when making a request to the route to gain authenticated access.
app.get('/secret', authenticateRequest, function(req, res){ res.send("Welcome to the secret area!"); });
Instructions
Declare authenticateRequest()
with three parameters: req
, res
, and next
above the Express route declarations using ES6 Arrow function expressions..
Create a new variable named request
and set it equal to a new instance of an OAuth2Server.Request
taking req
as an argument and create a new instance of an OAuth2Server.Response
taking res
as an argument and set it equal to response
.
Return oauth.authenticate()
passing request
and response
.
Use the .then()
method to return next()
.
Use the .catch()
to handle if the promise is rejected because of an error obtaining the token. Use the .send()
Express method to send “You are not allowed” to the client.
Add authenticateRequest
middleware to the /secret
route and if it exists send "Welcome to the secret area!"
back to the client.