Have a client login to their twitch account using the oauth (unity C#)

Basically, there’s A LOT of info on how to login in to YOUR twitch account for using chat, sub events etc, but I cant figure out to get a client to login, → kind of how you do on streamlabs and streamelements. You’re not logining in using streamelements client ID or secret but using their secret and YOUR ID.I have like 15 years coding experience but, this is my first day taking a crack at twitch API. Basically. the reason is, I want to get the users name, use the twitch name for leaderboards and their twitch Profile pic, also, an optional ability to follow ‘x-channel’ to gain a “supporters care package” etc. Kind of like plarium, netdragon, and devcat games have a tracker for facebook pages and they give you a gift when the token detects you follow their page. Also, I want to make a part of the game where streamers they follow come as random enemies, and HP has a calculation based on follower count. etc
code sample below →

 IEnumerator GetLogin()
    {                                                                                      //I don't know how I'm supposed to get the clients ID or how to open in another tab the login token you get from somewhere like streamelements.

        using (UnityWebRequest www = UnityWebRequest.Post("https://id.twitch.tv/oauth2/token","{\"this is where the client ID is suppopsed to go\":1, \"where the secret that I have goes?\":2}","application/json")){

        }
    }
}

If I didn’t explain it well enough, please ask me to reiterate whatever part doesn’t make sense. Thank you.

It’s all oAuth. Industry standard method to request access to resources on behalf of another user.

You open a web browser with your application ClientID
The user accepts/declines the account link
The user is returned to your application with an #access_token (since for a c# app guessing desktop solution so you would be useing implict auth not regular code flow so you don’t leak the Application secret)

Heres a JS Example of this

https://barrycarlyon.github.io/twitch_misc/authentication/implicit_auth/

Here you click [Connect with Twitch] which then grants my “GitHub Examples” Client ID permission to access your account.
Which then generates a token and I use that token to get your User information from the API

You are granting access to SE’s clientID to your account.
Using SE’s clientID, so this statement is contradictory to me.

Then SE can use generated credentails that represent you (or an app access/clients token for eventsub/some reasources) to access resources.

As you were typing that, I checked and noticed that you can get the tokens simply through application.OpenURL however, the example page Getting OAuth Access Tokens | Twitch Developers only gives examples for like 5-6 parameters, is there a FULL list a parameters somewhere? I can’t find it. Basically, I’m guessing I just read the json response, and store the token inside unity via a scriptableObj or something and use the helix commands? Which are just basically more https get/post requests? https://api.twitch.tv/helix/channels/followed etc. btw, this is all stuff I can do via WebGL(html5) right?? This is supposed to be a browser game not a game people have to download in order to give specific network permissions. lol cause I remember trying to develop a webGL multiplayer game a few years ago and some things with networking, webGL just WON’T do. Any potential issues I may have in the future? Or should all of this work in the intended scopes? I’ll be testing the application,openURL as soon as i finish this response.

That is the full list, what are you looking for that isn’t there?

With oAuth the user is redirected to “webpage” with a access token in the fragment (in the case if implicit auth.

Then you would use that token to call the API with yes.

Corrrect

Sure, it’s all JavaScript fetch requests

Then you’d be using implict auth most likely same as the code example I linked.

Well the first step is redirecting the user to Twitch

What is this referring to?

Also copy and paste from the streamlabs redirect:
response_type=code&client_id=8bmp6j83z5w4mepq0dn0q1a7g186azi&redirect_uri=https%3A%2F%2Fstreamlabs.com%2Fauth&scope=user_read+channel_subscriptions+user_subscriptions+user%3Aread%3Asubscriptions+chat%3Aread+channel_editor+bits%3Aread+channel%3Aread%3Asubscriptions+channel%3Aread%3Apolls+channel%3Amanage%3Apolls+channel%3Aread%3Astream_key+channel%3Amanage%3Abroadcast+channel%3Aedit%3Acommercial+channel%3Amanage%3Araids+moderator%3Aread%3Achatters+channel%3Aread%3Acharity+moderator%3Aread%3Afollowers+moderation%3Aread&state=b224749d6162e65ed1b182c72710e997ecbcd300-login

seems there is at least 10+ scopes and parameters here…

I’m like 1 1/2 hour into the doc on the twitch api and I think I get most of it but, there’s definitely still a few areas I’m not 100% sure on.

For the URL you pasted

  • response_type
  • client_id
  • redirect_uri
  • scope
  • state

5 parameters.

So you want the scopes list?

And you should generally only request the scopes you need, not all of them.

So check the API documentation for the endpoints you intend to call and the needed scopes. So far the only scope you appear to need, since you spoke about follows was moderator:read:followers

yeah, I’m just going to test myself using itch.io and make sure I can fetch, store, and post all/any data I MAY need without any permissions issues. cause of websocket mayhem.

I’ve have unity html5 throw tanrum over what seems like the most mundane networking stuff. Some of the issues I’ve had with what was considered “read/write” privileges was insane.

So, the code should basically be , field 1 is parameters(including the client Id from my app) and field 2 should be my secret?

using (UnityWebRequest www = UnityWebRequest.Post("https://id.twitch.tv/oauth2/token", "{\"Myparameters\":1, \"mysecret\":2}", "application/json")){

On your example, on github what language are you using? Cause I’m asking about C# specifics with webrequest.post etc the formatting on the website and the formatting on c#/.net are different and I’m trying my best to “assume” where things go after only having dev.twitch documentation to go off of. Really which sites would just give documentation in multiple languages like mongoDB and playfab do. It cuts the amount of time figuring out the steps by 1/10th. instead I have to “assume”.

basically, I need to fit this into Unity - Scripting API: Networking.UnityWebRequest.Post I can use const and convert strings into base64 for them to be read as bytes.
As I was typing this response I read different things in the twitch documentation that just got me confused again cause this is just jumping around the place. like, what am I going to be parsing in the response? like, this feels like, they could of made this into 3 pages and its just unnecessarily convoluted and All I need is a simple, using C# this is the response command, this is the tag your looking for, this is where you write secret/id in your web request, this is where you write parameters etc with a code example, I have an entire game to make with a Halloween deadline and I don’t want something that’s going to end up being 10 -15 lines of code taking up more than a day. Art alone is going to take a month. I tried looking at my old code from past games and everything was super clean cut. For some reason I got a math headache dealing with this. i’m just gonna nap and stream and come back to it later. No idea why they don’t have C# webrequest examples and are trying to get me to download so flipping “Curl” software. on the twitch documentation…

Javascript

It’s all HTTP requests, to which the lowest common denominator is cURL

Convert cURL requests into the relevant tool/library/program you are using for your language of chouce

Distributed applications potentially shouldn’t contain your secret. so you would be using implicit auth not something utilising a secret.

Convert the cURL request into the required format for the function you intend to use to make requests with.

Or consider a library for c# instead

-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id=<your client id goes here>&client_secret=<your client secret goes here>&grant_type=client_credentials'

I just need you to answer directly mate. Was seeing this same stuff with

etc. Not sure why you don’t just give a code example like some other do on this forum.

I do not know Curl I do not KNOW what the equivalent in C# is for these -H and -c responses. I cannot google it easily, twitch api is only used for TWITCH it’s not like the internet is breeming with documentation examples for twitch specific calls. Never even heard about Curl until 2 hours ago. Also, twitchlib is trying to wrap everything into their own little “NuGet” and I don’t want to spent 6 hours + reading through BS to find the answer to -h and -c. If I know how to parse field1 and field2 for this -h and -c thing then the parsing the www.ToString().Format() and looking for something called ```
“access_token”:


all this is done in .net by WWWForm, const/var, or byte[] gotta know which  one this is trying to get me to do. I'm assuming I can do it via WWWFrom and using form.AddField("Client_ID,ClientSeret") still not sure if paremeters are suppsed to be chained in the Client_ID field or, if I need to parse it differently hence why a C# code example would solve this immediately. I can only assume and If not parsed correctly. will just send errors


I tried this,

public IEnumerator GetAuthorization()
{
WWWForm Content = new WWWForm();
Content.AddField(TwitchTokenScopes, mySecret);

    using (UnityWebRequest www = UnityWebRequest.Post("https://id.twitch.tv/oauth2/token", Content))
    {
        yield return www.SendWebRequest();
        if(www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log(www.ToString());

        }
    }
}

there error in browser is,  {"status":400,"message":"missing response type"} 


so if you or anyone else reading this can just type in a code example given what I've said  then would be great here is the TwitchTokenScopes -> ?response_type=code&client_id=3oagpekjph2wq8dmd8fq9p7169u7mk &redirect_uri=http://localhost:3000&scope=user:edit:follows&scope=moderator:read:followers

btw I corrected my typo

 public IEnumerator GetAuthorization()
    {       
        WWWForm Content = new WWWForm();
        Content.AddField(TwitchTokenScopes, mySecret);

       
        using (UnityWebRequest www = UnityWebRequest.Post("https://id.twitch.tv/oauth2/authorize", Content)) //"{\"Content-Type:application/x-www-form-urlencoded\":1, \"client_id=<3oagpekjph2wq8dmd8fq9p7169u7mk>&client_secret=<REMOVED>&grant_type=client_credentials\":2}", "application/json")){
        {
            yield return www.SendWebRequest();
            if(www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.ToString());

            }
        }
    }

Still sending the same {“status”:400,“message”:“missing response type”}

Becuase I don’t know/write C# so I can’t literally write out C# code for you, so I give equivalent examples in another language if possible or link to an example that explains the work flow.

And/or I explain base principals instead

Except (what your question pertains to is) this is oAuth which is not unique to Twitch it’s a standard authentication method for a variety of services, including but not limited to

  • Twitch
  • Google
  • Facebook
  • Twitter/x

never used Oauth for anything that uses Curl, you can use selenium for Google, Facebook and twitter tho. At least as of 2021(Last time I used it). Can just get permissions to access the persons login catalog "apps that have been saved with auto-sign in. Or if not, send in a login request using the credentials someone types into your game. your browser basically stores EVERYTHING and you can usually just use that info and parse the website with json using the headers etc. like for youtube you just open the users

example with selenium;


(All you need is the dev tool on your browser to get it to navigate and use the read-only data)

selenium just gets fed the website name and looks through the indexes/headers and just goes through the table. Since the user gets prompted to login or, is already logged in, it can run this on a separate thread behind the scenes and gets the info required behind the scenes. Also, selenium has a NuGet for C# so, super easy/convenient but, twitch wraps so much of their info behind stuff that isn’t called unless “needed” so, you cant use this method with any stability. For twitch only so far in my experience. I’m only doing high level calls and need very basic info, never have needed to “edit” anything on behalf of a user so, no need for OAuth.

C#.NET - Access OAuth REST Web API Method I’ll read through this after streaming and try and just “assume” what pairs I need for the twitch version. This seems very similar to the stuff I did before but, again, I never needed a "client_d, usually its parsed like www.mongodb.com/AdminTableNumber + AdminPassword , mySecret twitch seems to have more entry requirements and seems to parse things a little differently.

Thank you for at least responding to the thread Barry. I do appreciate that.

For future forum viewers, I’ll be typing the C# answer to this thread when I get it later tonight. I’m ASSUMING I can do it in webGL and the Oauth website example is wrong and I don’t need the newton NuGet cause, if I did that means Oauth cant be used without making it a stand-alone with depenency packages… I’m ASSUMING I can make a toString().format and parse it like in the example json. and then send that through webrequest but, I won’t know until 6-7 hours from posting this cause like I said. about to stream. see you on the other side.

Okay so, I’m gotten a lot closer, I can get the non-return version to work using Application.OpenURL();
However, using the version to try and get a return of the token is throwing an error.

public IEnumerator GetAuthorization()
    {       
        WWWForm Content = new WWWForm();
        Content.AddField("?response_type=", "code");
        //Content.AddField("Content-Type:", "application/x-www-form-urlencoded");
        Content.AddField("&client_iD=", "3oagpekjph2wq8dmd8fq9p7169u7mk");
        Content.AddField("&redirect_uri=", "http://localhost:3000");
        Content.AddField("&scope=", "user:edit:follows");
        Content.AddField("&state=", "c3ab8aa609ea11e793ae92361f002671");
       /*
        // Content.AddField("client_secret=", "vpja0aju5sbxem2q9wtl3ppxztsa8o");
       */
       // Content.AddField("grant_type=", "client_credentials");
          //Content.AddField(TwitchTokenScopes, mySecret);


        using (UnityWebRequest www = UnityWebRequest.Post("https://id.twitch.tv/oauth2/authorize", Content)) //"{\"Content-Type:application/x-www-form-urlencoded\":1, \"client_id=<3oagpekjph2wq8dmd8fq9p7169u7mk>&client_secret=<REMOVED>&grant_type=client_credentials\":2}", "application/json")){
        {
            yield return www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.ToString());

            }
        }
    }

this returns : the below error message.

HTTP/1.1 401 Unauthorized
UnityEngine.Debug:Log (object)
TwitchOAuth/<GetAuthorization>d__8:MoveNext () (at Assets/Scripts/TwitchOAuth.cs:64)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)


If anyone can tell me what I need to add/remove so it stops throwing this error to where I can’t get localhost response, would be nice. thank you! I’m about 80% of the way to solving this i think.

I also removed the &state= but, made no difference

If you’re trying to do client-side OAuth, you’re using the wrong OAuth flow (you should be using implicit, not auth code) and you’re making the wrong type of request (you’re trying to POST as the first step, when you MUST send the user to that URL not try to make requests to it directly).

Selenium (last I checked) is a website testing tool.
It’s not really for what you are trying to use it for.
Thats the purpose of oAuth

You are trying to POST instead of directing the user to their browser to grant/deny access between their Twitch account and your clientID.

oAuth steps:

  1. user opens your tool/website/whatever
  2. user clicks “login with twitch”
  3. user is sent to Twitch on the /authorize url
  4. user access or denies access between the clientID and themself
  5. if accepted they are redirected back to you (either with a token or with a code to be exchanged for a token/refresh key set)

For you it will be a token in the fragment as you will likely be using implicit auth.

So the entry point likely is not a web form that is POST-ing. You need to invoke the users web browser. As if you run it inside the App the user cannot inspect SSL, have easy access to their password manager and Twitch security might deny your “browser client” having access to login at all.

oAuth covers reading protected information such as a channels followers.

oAuth is not just for editing data it’s for delegating access to protected user data on behalf of the user, not just modifying user data

If you want to continue with TwitchLib and having issues they have a dedicated room to TwitchLib on the libraries Discord - Twitch API

I think I get what your saying, so the application redirect? they hit “accept” then I send what? Cause If i do the “link” method I get asked to accept, but it just redirects me to localhost and I cant retrieve a token from the app. I’m using websocket with html5, how am I supposed to extract the token in a unity game when the routing is localhost and I don’t have a newtonsoft NuGet? I’ll ask simply is there any way to do this without extra dependencies? Cause if there isn’t then I know to stop trying and that this is a waste of my time. I’m trying to run this as a BROWSER game, games get WAY less plays when they require a download. which defeats the entire purpose of what I’m trying to accomplish.

image-2023-08-30-174346929 hosted at ImgBB — ImgBB image-2023-08-30-174430169 hosted at ImgBB — ImgBB

If a token is somehow stored in the browser itself maybe I can get that but, as I said 20 times already, This is my first rodeo with Oauth, because twitch is FORCING me to use it when other apps usually have work arounds considering the limitations on websocket driven networking. If there is a way to do this in C# without downloading dependencies I’d really just like it if someone could show me a step by step code example. I’m on the forum for a simple do this/doi that answer so i can get on with a project. I just want working code for this ONE thing so I can move on with this project. thank you.

So yeah just send me a code example of implicit for C# and the way to extract the data I need. Personally, I don’t care if it’s copy and paste if it’d in C# I’ll understand what it’s doing after giving it a read through. thank you.

If its a browser game, redirect the user to the page the game is running on. If you redirect to somewhere that doesnt exist such as localhost where the user isnt running a web server then of course it wont work.

As documented, the OAuth token is in the URL hash, which that page you’re running the game on should be able to access.

OAuth is an industry standard, its not some Twitch specific thing, it’s used by most major internet services that offer an API.

Could it be possible to access data in other ways that are more janky, unprofessional, and potentially breaking ToS/developer agreement by scraping or other means? Maybe, but you wont find assistance with that here as its not supported or the responsible way to go about accessing the API when industry standards exist that work perfecrly fine for game integration for many games, even web based.

1 Like