Lets make a Twitch Android app. Part 1. Tokens
Tags: android, mobile, kotlin, tristan
Published: 2023-07-15 19:40:22

### Table of contents
1. [The tokens needed](#token)
2. [Register your application](#reg)
3. [What is the OAuth Redirect URI](#what)
4. [Implicit grant flow](#grant)
5. [Making the request](#request)
6. [Collecting the response](#response)
7. [What is next](#next)

### The code
- [GitHub](https://github.com/thePlebDev/Clicker)

### YouTube version
- [YouTube](https://youtu.be/W9871XDzY1k)

### Introduction <a name="intro"></a>
- I have embarked on my next app, a Twitch client app. This series will be all my notes and problems faced when creating this app.


### Getting an access token <a name="token"></a>
- Before we can do anything cool with the twitch API, it is important to understand the two types of tokens the developers offer us. As all Twitch API endpoints require at least one of these two token types. 

**1) User access tokens :** Gives us access to APIs that require the user's permission to access. The upside to this type of token is that we can retrieve it through the [Implicit Grant flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow) and as the documentation states, we do not have to provide our client secret. Meaning that this type of token is perfect for apps without a server(like a mobile application). The downside is that the user has to be logged in before they can access any API data.`(this tutorial will be exploring this type of token)`

**2) App access tokens :** APIs that do not require the user's permission to access use this type of token. This type of token is acquired through the [authorization code grant flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow). The downside of this authentication process is that is requires the use of a `client_secret`. Meaning that we can not make our application 100% secure without using a reverse proxy server. However, the upside is that the user does not have to be logged in to their twitch account to access API data.`(this tutorial will not be covering this type of token)`
- Now that we have a brief understanding of what token we are using, we can move on to registering an application


### Register an application <a name="reg"></a>
- Now if we look at the [Registering Your App](https://dev.twitch.tv/docs/authentication/register-app/) documentation we can see that very first thing we need to do is to [create and register an application](https://dev.twitch.tv/console/apps/create), it will look something like this:

![demonstrating the process of registering twitch app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/22glb52gn7u14iqlq0l5.png)

- Now the name can be whatever you want, it just has to be unique within the Twitch developer ecosystem

- The section I want to draw your attention to is the `OAuth Redirect URIs`. If you have never heard of OAuth before, I recommend you watch this video, [HERE](https://www.youtube.com/watch?v=996OiexHze0), just make sure to watch it in 2x speed. If you are unfamiliar with the flow of an OAuth mobile application, then I would like to point you to on of my previous tutorials, found [HERE](https://dev.to/theplebdev/oauth20-and-android-login-with-github-and-get-the-authorization-code-40n3#what).

### What is the OAuth Redirect URI? <a name="what"></a>
- You might of noticed that I have used `https://peanutbutterjelly` as the redirect URI, but why? The only restrictive part of this URI is the `https`, as Twitch will not allow any other type of protocol. The `peanutbutterjelly` part is purely up to you, as there is no restrictions. However, it is common practice to use `com.yourappname`(what your application's name it)
- In order for us to utilize this `OAuth Redirect URI` properly we must use the proper [intent-filter](https://developer.android.com/guide/components/intents-filters). For this particular redirect URI the proper intent filter is:
```
<intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data
        android:host="peanutbutterjelly"
        android:scheme="https"
         />
</intent-filter>

```
- Notice how the `host` and `scheme` are the exact same as the redirect URI. They must follow this pattern:

`<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>|<pathAdvancedPattern>|<pathSuffix>]`

- That pattern can be found [HERE](https://developer.android.com/guide/topics/manifest/data-element)

#### Why do we need an intent filter?
- Well once our user logs into Twitch through the browser(we do this so our application does not know the user's username or password. Which is considered a best practice ). The Android OS will send out an [Implicit Intent](https://developer.android.com/guide/components/intents-filters#ExampleSend) looking for any applications that can handle an intent with the redirect URI of `https://peanutbutterjelly`

- You can tell if you messed up the intent filter if upon a successful login, the user is not directed back to your application, but instead tries to load the redirect uri in the browser. If that happens it means your intent filter is not properly implemented

### Implicit grant flow (user access token) <a name="grant"></a>
- Now that we know what token we are using and have an intent filter set up. we need to implement the [implicit grant flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow)


![Implicit flow grant documentation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yszydrs5qdd50jijqzyn.png)

- according to the documentation we need to make a request to `https://id.twitch.tv/oauth2/authorize` and provide it with parameters of `Client_it`, `redirect_uri`, `response_type` and `scope`. ultimately the request end point will look like this:

`https://id.twitch.tv/oauth2/authorize?client_id=$clientId&redirect_uri=$redirectUri&response_type=token&scope=user:read:follows`

- just simply replace `$clientId` and `$redirectUri` with the values unique to your application.
- The scopes can be found [HERE](https://dev.twitch.tv/docs/authentication/scopes/). I am using the `user:read:follows` which will allow me to view the list of channels a user follows. Now we just need to make a request

### Making the request <a name="request"></a>
- Now you might think that in order to make the request we are going to use [Retrofit](https://square.github.io/retrofit/) but in reality we are going to be sending out an implicit intent like so:
```

val twitchIntent = Intent(
    Intent.ACTION_VIEW, Uri.parse(
        "https://id.twitch.tv/oauth2/authorize?client_id=$clientId&redirect_uri=$redirectUri&response_type=token&scope=user:read:follows")
            )

Button(onClick ={startActivity(twitchIntent)},modifier = Modifier.align(Alignment.Center)) {
            Text("Login with Twitch", fontSize = 30.sp)
        }

```
- When the button is clicked an implicit intent will be created with `startActivity(twitchIntent)` and the user will be direct to the default browser application and will be asked to login

###Collecting a response <a name="response"></a>
- Technically speaking, we are going to be receiving an implicit intent and we have already set up the intent filter to do just that. But now we have to get the data from the intent
- To retrieve the response from the intent, we can do so inside the onResume() method:
```
override fun onResume() {
        super.onResume()
       val uri:Uri? = intent.data
        if(uri != null){
            Log.d("Twitch",uri.toString())
        }
    }

```
- If everything is done right we should get a response of:
```
https://peanutbutterjelly/#access_token=px4db8qo0uuaq75350id57h0ub6sze&scope=user%3Aread%3Afollows&token_type=bearer

```

### What is next? <a name="next"></a>
- In the next tutorial we will look at using this token to get access to all the streamers someone follows


### Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on [Twitter](https://twitter.com/AndroidTristan).