Created
August 19, 2023 10:59
-
-
Save cgsdev0/35ce479ac0c59facd3dbef2ba99e2ffc to your computer and use it in GitHub Desktop.
twitch identity provider flow
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
/////////////////////////// | |
// Client | |
/////////////////////////// | |
// when the user clicks the 'login with twitch' button... | |
document.location = | |
`https://id.twitch.tv/oauth2/authorize` + | |
`?client_id=${TWITCH_CLIENT_ID}` + | |
`&redirect_uri=${redirect}` + | |
`&response_type=token`; | |
// when you get redirected back to your app: | |
const hash = window.location.hash.replace('#', ''); | |
const params = new URLSearchParams(hash); | |
const twitch_access_token = params.get('access_token'); | |
// try to login on the server with the token | |
await window.fetch( | |
backendLoginEndpoint, | |
{ | |
body: JSON.stringify({ twitch_access_token }), | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
method: 'POST', | |
} | |
); | |
/////////////////////////// | |
// Server (login endpoint) | |
/////////////////////////// | |
const resp = await fetch("https://id.twitch.tv/oauth2/validate", { | |
headers: { Authorization: "Bearer " + twitch_access_token }, | |
}); | |
const { client_id, login, user_id } = await resp.json(); | |
if (client_id !== TWITCH_CLIENT_ID) { | |
throw new Error("client id mismatch"); | |
} | |
// Ask twitch for user details | |
const userDataResp = await fetch( | |
"https://api.twitch.tv/helix/users?id=" + user_id, | |
{ | |
headers: { | |
Authorization: "Bearer " + twitch_access_token, | |
"Client-Id": client_id, | |
}, | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment