как узнать свой токен твич
Ключ Твич (Twitch). Как узнать ключ потока вещания на Твиче или где найти (взять) ключ потока Твич для стрима
Где найти ключ потока вещания для стрима на Twitch.tv
После оформления и настройки канала на Твиче, необходимо правильно настроить OBS Studio для стрима. Чтобы трансляции заработала, необходимо указать в настройках ОБС ключ потока на Twitch.
Я вместе с командой запустил сервисы для стримеров на Twitch.tv:
Как найти ключ потока на Твиче
Для того чтобы получить ключ Твич, сперва надо будет пройти регистрацию на сайте Twitch.tv или же зайти под своим логином и паролем, созданным ранее.
Перейдите в «Информационную панель» канала Twitch. Это в правом верхнем углу, где написана ваше имя профиля.
Далее во вкладку «Настройки«. Если же у вас все на английском, то переключите язык сайта на русский.
Нажмите на «Ключ трансляции«.
Далее нажмите «Показать ключ» и откроется модальное окно.
Теперь следует нажать на кнопку «Понятно» и появится тот самый ваш ключ трансляции.
Здесь же вы можете сбросить ключ потока и получить новый.
Вам остается только скопировать ключ потока вещания Твича и вставить его в OBS Studio. Если у вас возникли вопросы, смело пишите их в комментарии к данному посту.
Где найти ключ потока (Stream Key) на Твиче и зачем он нужен
Ключ потока Твич — для кого-то известное, а для кого-то совсем новое понятие. Если вы только пришли в игру, эта статья поможет вам узнать, что значит этот инструмент, какую ценность несет, как применяется и что от него зависит.
Что такое ключ потока Twitch «Stream Key» и зачем он нужен
Twitch Stream Key — это персональный уникальный ключ потока трансляции, который нужен чтобы захватить всю картинку в программе OBS. Такого значения вы не найдете в открытом доступе, поскольку информация личная и запрещена для распространения. Его можно сравнить с данными паспорта или информацией для входа в аккаунт. А если другой юзер узнает код, без труда сможет зайти на вашу страницу и стримить свои игры оттуда. Ключ трансляции на Твиче изменяемый, поэтому если его случайно кто-то узнал или подсмотрел, значение можно обнулить и генерировать новое.
Где взять ключ потока на Твиче
Чтобы найти стрим кей, пройдите несколько пунктов:
Для того чтоб получить «Стрим Кей» включите двухфакторную аутентификацию!
После показа система отправляет вам диалоговое окно. Это сообщение в переводе с английского языка предупреждает вас о том, что публиковать или разглашать комбинацию нельзя, иначе это может повлечь потерю аккаунта или бан. Подтвердите что вы прочли оповещение и согласны с ним.
Stream Key для Youtube
Для любой трансляции есть своя площадка с данными для авторизации. Узнать его возможно по тому же алгоритму, потому что для одного аккаунта значение не имеет, куда будет подаваться эфир игры.
Stream Key на VK
Относительно недавно Социальная сеть «Вконтакте» официально включила функцию онлайн видеотрансляций. Если геймер решил передавать видео на платформу VKontakte, то потребуется также использовать данные авторизации.
Как сбросить «Stream Key»?
Действие занимает всего несколько секунд. Снова выполните алгоритм:
После того, как вы нажмете на «Сбросить», нижняя строчка обновится.
Please enable account for streaming to receive a Stream Key – что делать?
Дословно этот месседж от системы означает «Пожалуйста, включите учетную запись для видеопередачи, чтобы получить данные потока». Возникает Error тогда, когда вы либо не авторизировались, либо не прошли верификацию учетной записи. Для устранения бага выйдите из аккаунта, и совершите вход повторно. При необходимости, очистите файлы Куки с браузера, или верните ручные настройки до первоначальных.
Getting Tokens: OAuth
Introduction
There are three OAuth procedures:
See theВ Apps & Authentication GuideВ for an explanation of the different types of procedures.
OAuth implicit code flow
1)В Send the user you want to authenticate to your registered redirect URI. An authorization page will ask the user to sign up or log into Twitch and allow the user to choose whether to authorize your application/identity system.
There are several required and optional query-string parameters:
In our example, you request access to a user’s viewing activity (by specifying the viewing_activity_read  scope) and send the user to http://localhost :
2)В If the user authorizes your application, the user is redirected to your redirect URL:
The response includes theВ state В parameter, if it was in your request.
In our example, your user gets redirected to:
OAuth authorization code flow
1)В Send the user you want to authenticate to your registered redirect URI. Then, an authorization page will ask the user to sign up or log into Twitch and allow the user to choose whether to authorize your application/identity system. Use this request:
There are several required and optional query-string parameters:
In our example, you request access to a user’s viewing activity (by specifying the viewing_activity_read  scope) and send the user to http://localhost :
2)В If the user authorizes your application, the user is redirected to your redirect URI, with an authorization code:
The OAuth 2.0 authorization code is a 30-character, randomly generated string. It is used in the next step, a request made to the token endpoint in exchange for an access token.
The response includes theВ state В parameter, if it was in your request.
In our example, your user gets redirected to:
3)В On your server, get an access token by making this request:
Here is a sample request:
4)В We respond with a JSON-encoded access token. The response looks like this:
OAuth client credentials flow
As mentioned earlier, app access tokens are only for server-to-server API requests. The grant request below requires the client secret to acquire an app access token; this also should be done only as a server-to-server request, never in client code.
1)В On your server, get an app access token by making this request:
Here is a sample request:
There are several required and optional query-string parameters:
2)В We respond with a JSON-encoded app access token. The response looks like this:
Зачем нужен ключ потока Твич?
Что такое ключ потока Твич, зачем он нужен? Пора поговорить об одной из самых важных для ведения стрима вещей – если бы не этот код, вы не смогли бы начать трансляцию, не завели бы новых подписчиков, не смогли бы развивать канал! Подробно рассмотрим все доступные действия и дадим пошаговые инструкции для пользователей-новичков!
Где найти ключ
Ключ трансляции Твич – уникальное сочетание букв и цифр, необходимое для настройки трансляции. Этот достаточно длинный код всегда начинается с «live_», далее следует ряд произвольно сочетаемых чисел и латинских букв. Без него не обойтись, если вы хотите вести стримы!
Прежде чем разбираться, где ключ потока на Твиче, нужно понять – зачем он нужен? Вспомним технику проведения стримов:
Этот код подтверждает вашу личность и позволяет осуществить соединение без дополнительного ввода логина и пароля. Именно поэтому важно его беречь – об этом чуть позже. Пока поговорим о том, где взять ключ потока на Твиче: это несложно!
Возвращаемся к безопасности – как обещали! Вы нашли нужную страницу, но код потока закрыт звездочками? Требование безопасности – никто не должен случайно увидеть сгенерированный пароль.
Открыть его можно – щелкните по фиолетовой иконке «Показать», которая находится чуть ниже. Предварительно вы должны:
Где найти ключ трансляции Твич – рассказали. Разработчики предупреждают пользователей: никогда никому не сообщайте данные, не показывайте их во время трансляции – не верьте мошенникам, называющим себя службой поддержки или представителями платформы. Настоящие сотрудники стримингового сервиса не будут запрашивать такую информацию. Относитесь к ключу потока, как к пин-коду от банковской карты!
Где найти ключ потока на Твиче вы знаете – что можно с ним делать?
Как сбросить
Возникла необходимость срочно поменять данные? Это можно сделать – никаких ограничений. Вы уже знаете, где находится ключ потока Твич – он может быть изменен по первому требованию:
Мы рассказали вам, как узнать ключ потока на Твиче – это несложно! Не забывайте о правилах безопасности, никому не давайте доступ к личным данным – вы же не хотите потерять канал со всеми материалами и подписчиками? Будьте внимательны и стримьте в свое удовольствие!
Authentication
Introduction
This guide describes how to use Twitch Authentication to enable your application to take actions on behalf of a Twitch account or access certain data about users’ accounts. The preferred method of authentication is OAuth. We use parts of the OAuth 2.0 protocol.
In addition to OAuth, Twitch supports OIDC (OpenID Connect) for a more secure OAuth 2.0 flow. OIDC tokens are compatible with services built for OIDC compliance, such as Cognito by Amazon Web Services.
Code samples are available for Go and Node.js.
Warning: Treat your token like a password. For example, never use access tokens in any public URL, and never display tokens on any web page without requiring a click to de-obfuscate.
Validating requests
If you use Twitch authentication for login purposes only, access tokens should be validated on a recurring interval. Periodic validation of previously issued OAuth tokens ensures that users who authorized your application have not decided to disconnect the integration.
You must validate access tokens before making API requests which perform mutations on or access sensitive information of users, if it has been more than one hour since the last validation.
Twitch periodically conducts audits. If we discover an application that is not re-validating access tokens (that is, an application that validates only for login and not thereafter), we will reach out and work with developers to resolve the issue. If the issue is not resolved, we may take punitive action, such as revoking the developer’s API key or throttling the application’s performance.
Validation is important because of how OAuth access tokens work and the end user’s expectation of OAuth session control. For example, users who opt to disconnect your integration from their Twitch accounts can do so from their account settings on Twitch. When a user disconnects from an integration, all OAuth tokens between that user and that integration are invalidated. In this scenario, the expectation is that OAuth tokens are tied to sessions on third-party services; as such, any existing sessions between the disconnected user and those services also should be invalidated.
When validating each of your requests, submit a request to the validation endpoint ( https://id.twitch.tv/oauth2/validate ) with your OAuth token in the header. If you are authenticated, the response includes the status of your token. A successful response indicates that your access token is valid.
Here is a sample request:
And here is a sample response:
Registration
To make an application that uses the Twitch API, you first need to register your application on the Twitch developer site. When creating this app, enter your redirect URI, which is where your users are redirected after being authorized. You can provide several redirect URIs, for example, if you wish to use the same client for different environments.
Once you create a developer application, you are assigned a client ID. Some authentication flows also require a client secret, which you can generate on the same page as the client ID.
Because your client secret is confidential, we cannot show it to you once you leave the page, so make sure to record it somewhere safe. Also, generating a new client secret immediately invalidates the current one, which might make your API requests fail until your app is updated.
Warning: Client IDs should be unique for each application: do not re-use client IDs across multiple applications. Also, applications should request the appropriate scopes for the intended target APIs. Failure to adhere to these guidelines may result in the suspension of your application’s access to the Twitch API.
Types of tokens
Twitch supports several types of tokens:
Token Type | Description |
---|---|
ID tokens (OIDC) | A set of claims about the end user, for a given authorization. Using OIDC ID tokens (JWT) enables you to get details about your user (such as email address) for a particular authorization. These details are represented by claims in the ID token’s payload. Our discovery endpoint is at https://id.twitch.tv/oauth2/.well-known/openid-configuration. It can be used with standard OIDC clients like AWS Cognito. |
User access tokens | Authenticate users and allow your app to make requests on their behalf. If your application uses Twitch for login or makes requests in the context of an authenticated user, you need to generate a user access token. |
App access tokens | Authenticate your app and allow it to access resources that it owns. Since app access tokens are not associated with a user, they cannot be used with endpoints that require user authentication. Some Twitch API endpoints require application authentication (not user authentication). If your application uses these endpoints, you need to generate an app access token. App access tokens get client credentials (not user credentials). They enable you to make secure API requests that are not on behalf of a specific user. Client credentials also may be used in place of client ID headers to securely identify your application. App access tokens expire after about 60 days, so you should check that your app access token is valid by submitting a request to the validation endpoint (see Validating Requests). If your token has expired, generate a new one. App access tokens are meant only for server-to-server API requests and should never be included in client code. |
User access tokens and app access tokens are both bearer tokens. “Bearer” comes from the authorization header; see Sending User Access and App Access Tokens.
Getting tokens
The domain dedicated to Twitch authentication is https://id.twitch.tv.
Note: URLs have been updated to replace https://api.twitch.tv/kraken with https://id.twitch.tv. Code that uses the old kraken domain for Twitch authentication will continue to work until the removal of Twitch API v. 5 functionality. Twitch API v. 5 is currently deprecated.
We support several authentication flows:
Flow Type | Description |
---|---|
Implicit code flow | Your app does not use a server, such as a client-side JavaScript app or mobile app. This approach does not require a server that must make requests to the API. |
Authorization code flow | Your application uses a server, can securely store a client secret, and can make server-to-server requests. |
Client credentials flow | You need an app access token. |
The procedure you should use to get tokens depends on the type(s) of tokens you want:
Procedure | User Access Token | ID Token | App Access Token |
---|---|---|---|
OIDC Implicit Code Flow | вњ” | вњ” | В |
OAuth Implicit Code Flow | вњ” | В | В |
OIDC Authorization Code Flow | вњ” | вњ” | В |
OAuth Authorization Code Flow | вњ” | В | В |
OAuth Client Credentials Flow | В | В | вњ” |
Sending user access and app access tokens
When an API request requires authentication, send the access token as a header. The header differs, depending on which API you use:
Revoking access tokens
To clean up previously obtained access tokens, use the Twitch OAuth token-revocation endpoint. The implementation follows the OAuth standard.
The following example shows how to revoke a user or app access token:
Successful requests return 200 OK with no body.
Refreshing access tokens
New OAuth2 access tokens have expirations. Token-expiration periods vary in length, based on how the token was acquired. Tokens return an expires_in field indicating how long the token should last. However, you should build your applications in such a way that they are resilient to token authentication failures. In other words, an application capable of refreshing tokens should not need to know how long a token will live. Rather, it should be prepared to deal with the token becoming invalid at any time.
To allow for applications to remain authenticated for long periods in a world of expiring tokens, we allow for sessions to be refreshed, in accordance with the guidelines in “Refreshing an Access Token” in the OAuth2 RFC. Generally, refresh tokens are used to extend the lifetime of a given authorization.
Note: App access tokens and ID tokens cannot be refreshed.
How to refresh
To refresh a token, you need an access token/refresh token pair coming from a body. For example:
You also need the client_id and client_secret used to generate the above access token/refresh token pair
To refresh, use this request:
There are several required parameters and one optional parameter:
Your refresh token may contain characters that are not URL safe, so be sure to URL encode the characters of your refresh token before inserting it into the body of the refresh request. Otherwise, you may get an error (“Invalid refresh token”) when you try to refresh.
Optional Parameter | Type | Description |
---|---|---|
scope | string | Space-separated list of scopes. This must be the entire set or any subset of the scopes assigned to the original token grant. It cannot include any scope not originally granted by the resource owner. Default: the entire set of scopes originally granted. |
Here is a sample response on success. It contains the new access token, refresh token, and scopes associated with the new grant. Your application should then update its record of the refresh token to be the value provided in this response, as the refresh token may change between requests.
Here is the body of an unsuccessful response:
Refresh in response to server rejection for bad authentication
We recommend that you refresh your tokens in response to being rejected by the server for bad authentication. It is good practice to assume that your access token can expire or be revoked at any time, and refreshing reactively ensures that your application is prepared to deal with such situations as gracefully as possible. For this reason, refreshing in response to server rejection is preferable to refreshing proactively, on a fixed schedule.
When you make a request with expired or incorrect authorization credentials, the API returns a 401 Unauthorized status:
On seeing a 401 error, an application should try to refresh the session if a refresh token is present. If the refresh fails, the application should re-prompt the end user with another authentication dialog via the standard OAuth 2 flow.
Handling token refreshes in an application
We recommend that you do access-token refreshes synchronously with respect to all consumers of a given access token. That is, do not send multiple, simultaneous refresh requests for the same token. Send one refresh request, then redistribute the new token that is returned from that request to all consumers, as appropriate.
The API limits the number of active access tokens associated with a given refresh token. The limit is 50 token per client/user (that is, a user can only have 50 tokens live at a time per client ID). If multiple threads sharing the same authorization were to simultaneously refresh, some of them might not have working credentials at the end of the refresh. Synchronizing on the refresh operation prevents the application from inadvertently overrunning its limit.
Scopes
As mentioned above, when you request authorization from users, the URL scope parameter allows you to specify which permissions your app requires. These scopes are tied to the access token you receive on successful authorization. Multiple scopes can be specified when requesting an OAuth or OIDC token. Without specifying scopes, your app can access only basic information about the authenticated user.
Scopes are specified as a space-separated list in the URL scope parameter, when requesting authorization:
Ask only for the permissions you need, as users can view each requested permission when authorizing your app.
No scopes are needed when requesting app access tokens.
Twitch API
The table below is a comprehensive list of the available scopes for the Twitch API. To see a comprehensive list of all Twitch API endpoints, including those that do not require scopes, refer to the Twitch API reference.
Scope Name | Type of Access and Associated Endpoints |
---|---|
analytics:read:extensions | View analytics data for the Twitch Extensions owned by the authenticated account. Get Extension Analytics |
analytics:read:games | View analytics data for the games owned by the authenticated account. Get Game Analytics |
bits:read | View Bits information for a channel. Get Bits Leaderboard |
channel:edit:commercial | Run commercials on a channel. Start Commercial |
channel:manage:broadcast | Manage a channel’s broadcast configuration, including updating channel configuration and managing stream markers and stream tags. Modify Channel Information |
channel:manage:extensions | Manage a channel’s Extension configuration, including activating Extensions. Get User Active Extensions |
channel:manage:polls | Manage a channel’s polls. Create Poll |
channel:manage:predictions | Manage of channel’s Channel Points Predictions Create Channel Points Prediction |
channel:manage:redemptions | Manage Channel Points custom rewards and their redemptions on a channel. Create Custom Rewards |
channel:manage:schedule | Manage a channel’s stream schedule. Update Channel Stream Schedule |
channel:manage:videos | Manage a channel’s videos, including deleting videos. Delete Videos |
channel:read:editors | View a list of users with the editor role for a channel. Get Channel Editors |
channel:read:goals | View Creator Goals for a channel. Get Creator Goals |
channel:read:hype_train | View Hype Train information for a channel. Get Hype Train Events |
channel:read:polls | View a channel’s polls. Get Polls |
channel:read:predictions | View a channel’s Channel Points Predictions. Get Channel Points Predictions |
channel:read:redemptions | View Channel Points custom rewards and their redemptions on a channel. Get Custom Reward |
channel:read:stream_key | View an authorized user’s stream key. Get Stream Key |
channel:read:subscriptions | View a list of all subscribers to a channel and check if a user is subscribed to a channel. Get Broadcaster Subscriptions |
clips:edit | Manage Clips for a channel. Create Clip |
moderation:read | View a channel’s moderation data including Moderators, Bans, Timeouts, and Automod settings. Check AutoMod Status |
moderator:manage:automod | Manage messages held for review by AutoMod in channels where you are a moderator. Manage Held AutoMod Messages |
user:edit | Manage a user object. Update User |
user:edit:follows | Deprecated. Was previously used for “Create User Follows” and “Delete User Follows.” See Deprecation of Create and Delete Follows API Endpoints. |
user:manage:blocked_users | Manage the block list of a user. Block User |
user:read:blocked_users | View the block list of a user. Get User Block List |
user:read:broadcast | View a user’s broadcasting configuration, including Extension configurations. Get Stream Markers |
user:read:email | View a user’s email address. Get Users (optional) |
user:read:follows | View the list of channels a user follows. Get Followed Streams |
user:read:subscriptions | View if an authorized user is subscribed to specific channels.Legacy Twitch API v5With the deprecation of Twitch API v5, the scopes below have been mapped to Twitch API scopes for an easier migration between versions. You can find this mapping and information about equivalent endpoints on the Twitch API Migration Guide.
|