Now that our model functions for generating and saving access tokens are implemented in model.js, we need to create a callback function to handle obtaining the access token whenever a URL is requested in our application. Within app.js, we create a function named obtainToken()
that takes the HTTP request and HTTP response as arguments—req
and res
.
Inside obtainToken()
, we create a new variable named request
and set it to a new instance of OAuth2Server.Request()
, passing the HTTP request, req
, as the argument:
let request = new OAuth2Server.Request(req);
We’ll also create a new variable named response
and set it to a new instance of OAuth2Server.Response()
, taking in res
as the argument:
let response = new OAuth2Server.Response(res);
The .token()
method of the oauth
object returns the access token. The method passes the OAuth2Server
‘s request and response stored in response
and request
variables. We use the .then()
method to return a promise. If the token method is successful, we will send the access token back to the client using the .json()
Express method.
const obtainToken = (req, res) => { let request = new OAuth2Server.Request(req); let response = new OAuth2Server.Response(res); return oauth.token(request, response) .then((token) => { res.json(token); }) }
We’ll chain the .catch()
method to handle any errors if the .token()
method fails. If the .token()
method returns an error code or an HTTP 500 status, the error can be sent back to the client using the .json()
method.
.catch((err) => { res.status(err.code || 500).json(err); });
Note, must declare our function expressions before they can be used. To make use of our obtainToken()
function, we can define a new route and pass obtainToken()
as a callback function. We use the .all()
method to handle all types of HTTP requests since we will eventually use a POST request on the route. The route name can be anything we’d like—we’ll use /auth
for our example.
app.all('/auth', obtainToken);
Now the client can make an HTTP request with the Client Secret to /auth
and receive an access token.
Instructions
Declare obtainToken()
function with two parameters: req
and res
.
Create a new variable named request
and set it equal to a new instance of an OAuth2Server.Request
object taking req
as an argument.
Then create a new instance of an OAuth2Server.Response
object taking res
as an argument and set it equal to response
.
Return oauth.token()
passing request
and response
.
Use the .then()
method to return a promise that sends a JSON response of the token using res.json()
.
Use the .catch()
method to return the error if the promise is rejected because of an error obtaining the token.
Create a new route to /auth
and call the obtainToken()
function.