Last active
November 18, 2020 10:34
-
-
Save t-davies/2e40373219b43090b5909e0cad73fbb1 to your computer and use it in GitHub Desktop.
Slightly messy reference for implementing client-side OAuth 2 flow in a CLI app
This file contains 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
// quick and dirty reference for oauth flow in CLI apps | |
let server: http.Server; | |
const recievedCode = new Promise<string>((resolve, reject) => { | |
server = http.createServer((req, res) => { | |
const { pathname, searchParams } = new URL( | |
req.url, | |
"http://localhost:3000/" | |
); | |
if (pathname.includes("oauth")) { | |
console.log({ | |
message: "got oauth callback", | |
parameters: searchParams.toString(), | |
}); | |
if (searchParams.has("code")) { | |
resolve(searchParams.get("code")); | |
} else { | |
reject("bad oauth response"); | |
} | |
res.writeHead(200, "OK"); | |
res.end(); | |
} else { | |
res.writeHead(200, "OK"); | |
res.write(`signed in`); | |
res.end(); | |
} | |
}); | |
server.listen(3000); | |
}); | |
open( | |
`https://id.twitch.tv/oauth2/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent( | |
"http://localhost:3000/oauth" | |
)}&response_type=code&scope=${encodeURIComponent( | |
["channel:manage:broadcast", "analytics:read:extensions"].join(" ") | |
)}&login_hint=${username}&hint=${username}` | |
); | |
const code = await recievedCode; | |
server.close(); | |
console.log({ | |
message: "exchanging access code for token", | |
code, | |
}); | |
const response = await fetch( | |
`https://id.twitch.tv/oauth2/token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}&grant_type=authorization_code&redirect_uri=${encodeURIComponent( | |
"http://localhost:3000/" | |
)}`, | |
{ | |
method: "POST", | |
} | |
); | |
if (response.ok) { | |
try { | |
const body = await response.json(); | |
console.log({ message: "successfully got access token" }); | |
return body.access_token; | |
} catch (err) { | |
console.log({ | |
message: "failed to parse sign in response", | |
error: err, | |
}); | |
} | |
} else { | |
try { | |
console.log({ | |
message: "bad request to token endpoint", | |
body: await response.json(), | |
}); | |
} catch {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm install open