Last active
August 21, 2018 12:58
-
-
Save wei0831/f740c28b96404495e776ea8c1836d1e7 to your computer and use it in GitHub Desktop.
Twitch OAuth Token Flow
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
func main() { | |
// local server to capture token | |
go startSever() | |
openBrowser(fmt.Sprintf("https://id.twitch.tv/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=token&scope=%s", clientID, redirectURI, scope)) | |
// TODO | |
for{ | |
} | |
} | |
func startSever() { | |
r := mux.NewRouter() | |
r.HandleFunc("/twitch/", tokenHandler) | |
r.HandleFunc("/twitch/toekn", getTokenHandler) | |
log.Fatal(http.ListenAndServe(":8080", r)) | |
} | |
// Redirect to capture the hash params | |
func tokenHandler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte(fmt.Sprintf(`<script> | |
window.location.replace("http://127.0.0.1:8080/twitch/toekn" + document.location.hash.replace("#", "?")) | |
</script>`))) | |
} | |
// Get query params | |
func getTokenHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Println(r.URL.Query()) | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte(`<script> | |
close() | |
</script>`)) | |
} | |
func openBrowser(url string) bool { | |
url = strings.Replace(url, "&", "^&", -1) | |
var args []string | |
switch runtime.GOOS { | |
case "darwin": | |
args = []string{"open"} | |
case "windows": | |
args = []string{"cmd", "/c", "start"} | |
default: | |
args = []string{"xdg-open"} | |
} | |
cmd := exec.Command(args[0], append(args[1:], url)...) | |
return cmd.Start() == nil | |
} |
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
func main() { | |
client := &http.Client{} | |
req, _ := http.NewRequest("GET", "https://id.twitch.tv/oauth2/validate", nil) | |
req.Header.Add("Authorization", fmt.Sprintf("OAuth %s", s)) | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer resp.Body.Close() | |
res, _ := ioutil.ReadAll(resp.Body) | |
// Print raw string of res | |
fmt.Println(string(res)) | |
// Print json data of res | |
var data map[string]interface{} | |
err = json.Unmarshal([]byte(res), &data) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment