Twitch Auth using WPF and C#

Posted by admin on December 31st, 2016

I’ve just spent a bit of time since I released the first build of a new streaming tool trying to understand Twitch oAuth mechanisms. I ran into a few problems along the way but learnt loads so I thought I’d write a quick post.

First I ended up writing a sample which shows how to use WPF and C# to get an oAuth Token from Twitch, hopefully it’s fairly well documented and you can find it here:

https://github.com/adrianschofield/TwitchAuthWPF

While writing this I learned a few interesting things which I’ll note down in the vague hope I’ll learn something.

Exception handling in Windows applications is a bit odd and because I was “catching and throwing” the exception was effectively suppressed even when the Debugger was running. I was really surprised that the Debugger didn’t catch them but the only way I could see them was to add a breakpoint in the catch block and look at the exception.  Lesson learned and not something that’s really a worry in real world programming but with a sample I didn’t want to make it any more cluttered than I needed to by adding debug logging and stuff like that.

Updating a value in a Window from a separate class is a pain in the proverbial. You need to do two things, data bind and manage the changes using INotifyPropertyChange and second you need to pass a reference to the MainWindow into your class so that it’s accessible. You can see this in action in the sample.

OK so what does the sample do?

Breaking the process down into steps like this helped me clarify what I needed to do:

1) Spin up your web server listening to the url you configured as your redirect url in your Twitch application settings
2) Send the user to the Auth URL using your WebBrowser control
3) The user will have to enter their credentials, and maybe Two Factor auth details
4) On a successful attempt your web server should then get a callback
5) The callback for Authorization Code Flow contains a code
6) Make the final POST to Twitch and get the oAuth token back in the Json response.

If you want to try the sample then you’ll need to create your own Twitch Application because oAuth requires the client secret which I have changed from the published source code so now the sample will no longer work as it stands. Update the values at the top of Program.cs to reflect your Twitch Developer application.

When you start the application press the “Authorize Me” button and you should be taken to a Twitch Login page. Enter your details and then the sample will populate the Text Box at the bottom of the window with your access_token. In the real world you’d never share this but you can use it inside your code to make authenticated requests to Twitch.

Any questions please do let me know either via comments, Twitter DM or raise an issue on the GitHub repo.

 

/* */