Skip to content

Instantly share code, notes, and snippets.

@gijswijs
Created February 18, 2019 06:49
Show Gist options
  • Save gijswijs/53b98596f5f1fb1d5c9b5eb4c3dc264c to your computer and use it in GitHub Desktop.
Save gijswijs/53b98596f5f1fb1d5c9b5eb4c3dc264c to your computer and use it in GitHub Desktop.
Azure function that functions as a proxy for exchanging the oAuth code for an access token
const request = require('request');
const config = {
clientId: 'xxx',
clientSecret: 'xxx',
redirectUri: 'http://localhost:8080/',
allowedOrigins: ['http://localhost:8080', 'http://127.0.0.1:8080'],
};
const handler = function (context) {
// Retrieve the request, more details about the event variable later
const headers = context.req.headers;
const body = JSON.parse('{"' + decodeURI(context.req.body).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
const origin = headers.origin || headers.Origin;
// Check for malicious request
if (!config.allowedOrigins.includes(origin)) {
throw new Error(`${headers.origin} is not an allowed origin.`);
}
const url = 'https://github.com/login/oauth/access_token';
const options = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
code: body.code,
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectUri,
}),
};
// Request to GitHub with the given code
request(url, options, function(err, response) {
if (err) {
context.done({ status: 500, error: err });
return;
}
context.res = {
status: 200,
body: JSON.parse(response.body),
headers: { 'Content-Type': 'application/xml' },
isRaw: true
};
context.done();
});
};
module.exports = handler
@gijswijs
Copy link
Author

Kevin Maschtaler came up with this idea in this post: https://www.kmaschta.me/blog/2017/03/04/github-oauth-authentication-without-server/
I ported his AWS Function to an Azure function.

@giacomocerquone
Copy link

giacomocerquone commented Feb 18, 2019

I've commented on his blog post too. For sure you could answer me too.

I don't know how azure or aws lambda works since I've never used them, but from his explanation I absolutely don't understand how the hell do you get the github code to make the request in order to exchange it for a token.
The only way I understood how to make it work in a SPA app is showed in this post here: http://blog.vjeux.com/2012/... and it makes use of the window.postmessage
I don't understand his concept since the code is given to the callback url you set on the github app page, and without a server, which url you put in? You could put this function, but it does accept only calls from the spa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment