Created
August 2, 2020 12:33
-
-
Save anishsujanani/64339e7d99f89e128fe7f03180fa8c2e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // this endpoint recieves a code and a state | |
| // checks if state matches the state_cache ie. has a request gone out and is a code awaited? | |
| // if so, get the code from the query_string, exchange that once again with the auth server for an actual token | |
| // why is this done? - Code for Token exchange is done on a secure back-channel | |
| app.get('/oauth_callback', (req, res) => { | |
| // make sure that a request has gone out, and that we are actually awaiting a code | |
| // and unsolicited responses are not being serviced | |
| if (!state_cache.includes(req.query.state)) { | |
| res.send('State has changed, either the flow took too long or CSRF'); | |
| } | |
| else { | |
| // send a POST request to the authorization server over a secure channel | |
| // to the endpoint that takes codes and gives back access tokens | |
| token_request_form = { | |
| grant_type: 'authorization_code', | |
| code: req.query.code, | |
| redirect_uri: redirect_uri, | |
| client_id: client_id, | |
| client_secret: client_secret | |
| } | |
| // send the request, if successful, we take the access token out of the body | |
| // and remove the state from the cache, ie. the flow is complete | |
| // this token can then be used to access the resources it was scoped to that the client consented to | |
| request.post({url: auth_server_token_endpoint, form: token_request_form}, (err, httpResponse, httprespbody) => { | |
| var auth_server_pub_key = fs.readFileSync('auth_server_pub.pem'); | |
| var decoded_token = jwt.verify(httprespbody, auth_server_pub_key, (err, decoded) => { | |
| if (err) { | |
| res.send(err); | |
| } | |
| else { | |
| res.send(decoded); | |
| state_cache = state_cache.filter(item => item !== req.body.code) | |
| } | |
| }); | |
| }); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment