go_twitchAuth

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2025 License: MIT Imports: 10 Imported by: 0

README

Golang Twitch Authentication Wrapper

A wrapper around Twitch's primary OAuth authentication flows.

Features

  • Support for the following OAuth grant flows:
    • Implicit Code grant flow
    • Authorization Code grant flow
    • Client Credentials grant flow
  • Token validation and revocation

[!IMPORTANT] Device Code Grant Flow is currently not supported. My intention with this library is to provide a fairly simple wrapper around the more common authentication flows.

Project Status

Still a work in progress. I am still actively working on cleaning up, simplifying, and documenting various pieces of this library.

There are also a handful of items that I intend to implement in the near future:

  • TESTS
  • Token refreshes when following the Authorization Code Grant flow

Installation

go get github.com/adamsurek/go-twitchAuth

Usage

Implicit Code Grant Flow
package main

import (
  ta "github.com/adamsurek/go-twitchAuth"
  "log"
)

func main() {
  // Define the scopes you'd like the user to authorize
  s := []ta.ScopeType{
    ta.ScopeUserReadChat,
    ta.ScopeUserReadEmotes,
    ta.ScopeUserReadFollows,
    ta.ScopeUserReadSubscriptions,
    ta.ScopeUserManageWhispers,
  }

  // Initialize the authenticator
  a := ta.NewImplicitGrantAuthenticator(
    "{YOUR_CLIENT_ID}",    // Client ID
    true,                  // Force Verify?
    "{YOUR_REDIRECT_URI}", // Redirect URI
    s,                     // Scopes
    "{STATE}",             // State
  )

  // Generate an authorization URL that the user can follow to authorize your app
  u, err := a.GenerateAuthorizationUrl()
  if err != nil {
    log.Fatalf("failed to generate auth url: %s", err)
  }

  // Provide URL to user
  log.Println(u.String())
  
  // ...Retrieve token after user has authorized app
}

Authorization Code Grant Flow
package main

import (
  ta "github.com/adamsurek/go-twitchAuth"
  "log"
)

func main() {
  // Define the scopes you'd like the user to authorize
  s := []ta.ScopeType{
    ta.ScopeUserReadChat,
    ta.ScopeUserReadEmotes,
    ta.ScopeUserReadFollows,
    ta.ScopeUserReadSubscriptions,
    ta.ScopeUserManageWhispers,
  }

  // Initialize the authenticator
  a := ta.NewAuthorizationCodeGrantAuthenticator(
    "{YOUR_CLIENT_ID}",     // Client ID
    "{YOUR_CLIENT_SECRET}", // Client Secret
    true,                   // Force Verify?
    "{YOUR_REDIRECT_URI}",  // Redirect URI
    s,                      // Scopes
    "{STATE}",              // State
  )

  // Generate an authorization URL that the user can follow to authorize your app
  u, err := a.GenerateAuthorizationUrl()
  if err != nil {
    log.Fatalf("failed to generate auth url: %s", err)
  }

  log.Println(u.String())

  // ...Provide auth URL to user
  // ...Retrieve authorization code from Twitch to your redirect URL

  // Exchange code for token
  t, err := a.GetToken("{CODE_FROM_TWITCH}")
  if err != nil {
    log.Fatalf("failed to send code exchange request: %s", err)
  }

  // Ensure that the exchange returned a token
  if t.TokenRequestStatus == ta.StatusSuccess {
    log.Println(t.TokenData.AccessToken)
  } else {
    // ex.: 400 - Invalid authorization code
    log.Fatalf("exchange did not succeed: %d - %s", t.FailureData.Status, t.FailureData.Message)
  }
}

Client Credentials Grant Flow
package main

import (
	ta "github.com/adamsurek/go-twitchAuth"
	"log"
)

func main() {
	// Initialize the authenticator
	a := ta.NewClientCredentialsGrantAuthenticator(
		"{YOUR_CLIENT_ID}",     // Client ID
		"{YOUR_CLIENT_SECRET}", // Client Secret
	)

	// Request token from Twitch API
	t, err := a.GetToken()
	if err != nil {
		log.Fatalf("failed to send token request: %s", err)
	}

	// Ensure that the response contains a token
	if t.TokenRequestStatus == ta.StatusSuccess {
		log.Println(t.TokenData.AccessToken)
	} else {
		// ex.: 403 - invalid client secret
		log.Fatalf("token request did not succeed: %d - %s", t.FailureData.Status, t.FailureData.Message)
	}
}
Validating and Revoking Tokens
package main

import (
  ta "github.com/adamsurek/go-twitchAuth"
  "log"
)

func main() {
  // Send token to Twitch API for validation
  v, err := ta.ValidateToken("{YOUR_TOKEN}")
  if err != nil {
    log.Fatalf("failed to send token validation request: %s", err)
  }

  // Confirm that token is valid
  if v.ValidationStatus == ta.StatusSuccess {
    log.Printf("token valid for user %s. expires in %d seconds",
      v.ValidationData.Login, v.ValidationData.ExpiresIn)
  } else {
    // ex.: 401 - invalid access token
    log.Fatalf("token invalid: %d - %s", v.FailureData.Status, v.FailureData.Message)
  }

  // Send token revocation request
  r, err := ta.RevokeToken("{YOUR_CLIENT_ID}", "{YOUR_TOKEN")
  if err != nil {
    log.Fatalf("failed to send token revocation request: %s", err)
  }

  // Confirm that revocation was successful
  if r.RevocationStatus == ta.StatusSuccess {
    log.Println("token revoked")
  } else {
    // ex.: 400 - token Invalid token
    log.Fatalf("failed to revoke token: %s", err)
  }
}

Documentation

Index

Constants

View Source
const (
	// StatusFailure signifies a failed Helix API request status (ex. HTTP 400).
	StatusFailure responseStatus = iota
	// StatusSuccess signifies a successful Helix API request status (ex. HTTP 200).
	StatusSuccess
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessTokenRequestResponse added in v0.1.3

type AccessTokenRequestResponse struct {
	AccessToken  string      `json:"access_token"`
	RefreshToken string      `json:"refresh_token"`
	ExpiresIn    int         `json:"expires_in"`
	TokenType    string      `json:"token_type"`
	Scopes       []ScopeType `json:"scopes"`
}

AccessTokenRequestResponse stores the parsed JSON response of an access token request.

type AuthorizationCodeGrantAuthenticator

type AuthorizationCodeGrantAuthenticator struct {
	// contains filtered or unexported fields
}

AuthorizationCodeGrantAuthenticator allows for the generation of an authorization URL following Twitch's OAuth client credentials grant flow.

New instances of AuthorizationCodeGrantAuthenticator should be created via NewAuthorizationCodeGrantAuthenticator.

Twitch docs: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow

func NewAuthorizationCodeGrantAuthenticator

func NewAuthorizationCodeGrantAuthenticator(clientId string, clientSecret string, forceVerify bool, redirectUri string, scopes []ScopeType, state string) *AuthorizationCodeGrantAuthenticator

NewAuthorizationCodeGrantAuthenticator generates a new AuthorizationCodeGrantAuthenticator instance.

func (*AuthorizationCodeGrantAuthenticator) GenerateAuthorizationUrl

func (a *AuthorizationCodeGrantAuthenticator) GenerateAuthorizationUrl() (*url.URL, error)

GenerateAuthorizationUrl builds a url.URL that allows a user to authorize a Twitch app and generate a bearer token.

func (*AuthorizationCodeGrantAuthenticator) GetScopes added in v0.1.4

GetScopes retrieves the currently requested list of scopes. It's important to note that the scopes returned are only what has been supplied to the authenticator - not what the end user has authorized.

To retrieve the scopes that the user has authorized, you can use the ValidateToken function.

func (*AuthorizationCodeGrantAuthenticator) GetToken

GetToken retrieves a new bearer token via the Twitch Helix API using the auth code generated when the user follows the authorization URL.

func (*AuthorizationCodeGrantAuthenticator) UpdateScopes

func (a *AuthorizationCodeGrantAuthenticator) UpdateScopes(scopes []ScopeType) (*url.URL, error)

UpdateScopes replaces the original array of ScopeType provided during initialization

type ClientCredentialsGrantAuthenticator

type ClientCredentialsGrantAuthenticator struct {
	ClientId     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	GrantType    string `json:"grant_type"`
}

ClientCredentialsGrantAuthenticator allows for the generation of an authorization URL following Twitch's OAuth client credentials grant flow.

New instances of ClientCredentialsGrantAuthenticator should be created via NewClientCredentialsGrantAuthenticator.

Twitch docs: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow

func NewClientCredentialsGrantAuthenticator

func NewClientCredentialsGrantAuthenticator(clientId string, clientSecret string) *ClientCredentialsGrantAuthenticator

NewClientCredentialsGrantAuthenticator generates a new ClientCredentialsGrantAuthenticator instance.

func (*ClientCredentialsGrantAuthenticator) GetToken

GetToken retrieves a new bearer token via the Twitch Helix API.

type FailedRequestResponse added in v0.1.3

type FailedRequestResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
}

FailedRequestResponse stores the parsed JSON response of a failed Helix API response.

type ImplicitGrantAuthenticator

type ImplicitGrantAuthenticator struct {
	// contains filtered or unexported fields
}

ImplicitGrantAuthenticator allows for the generation of an authorization URL following Twitch's OAuth implicit grant flow.

New instances of ImplicitGrantAuthenticator should be created via NewImplicitGrantAuthenticator.

Twitch docs: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow

func NewImplicitGrantAuthenticator

func NewImplicitGrantAuthenticator(clientId string, forceVerify bool, redirectUri string, scopes []ScopeType, state string) *ImplicitGrantAuthenticator

NewImplicitGrantAuthenticator generates a new ImplicitGrantAuthenticator instance.

func (*ImplicitGrantAuthenticator) GenerateAuthorizationUrl added in v0.1.4

func (a *ImplicitGrantAuthenticator) GenerateAuthorizationUrl() (*url.URL, error)

GenerateAuthorizationUrl builds a url.URL that allows a user to authorize a Twitch app and generate a bearer token.

func (*ImplicitGrantAuthenticator) GetScopes added in v0.1.4

func (a *ImplicitGrantAuthenticator) GetScopes() []ScopeType

GetScopes retrieves the currently requested list of scopes. It's important to note that the scopes returned are only what has been supplied to the authenticator - not what the end user has authorized.

To retrieve the scopes that the user has authorized, you can use the ValidateToken function.

func (*ImplicitGrantAuthenticator) UpdateScopes

func (a *ImplicitGrantAuthenticator) UpdateScopes(scopes []ScopeType)

UpdateScopes replaces the original array of ScopeType provided during initialization

type ScopeType added in v0.1.3

type ScopeType int

ScopeType represents the level of access an app has on the Twitch API.

Full list of scopes: https://dev.twitch.tv/docs/authentication/scopes/

const (
	// ScopeAnalyticsReadExtensions allows app to view analytics data for the Twitch extensions owned by the
	// authenticated account.
	ScopeAnalyticsReadExtensions ScopeType = iota + 1

	// ScopeAnalyticsReadGames allows app to view analytics data for the games owned by the authenticated account.
	ScopeAnalyticsReadGames

	// ScopeBitsRead allows app to view bits information for a channel.
	ScopeBitsRead

	// ScopeChannelBot allows app to join the user's channel as a bot user and perform chat-related actions.
	ScopeChannelBot

	// ScopeChannelManageAds allows app to manage the ads schedule on a channel.
	ScopeChannelManageAds

	// ScopeChannelReadAds allows app to read the ads schedule and details on the user's channel.
	ScopeChannelReadAds

	// ScopeChannelManageBroadcast allows app to manage a channel's broadcast config, including updating channel config
	// and managing stream markers and tags.
	ScopeChannelManageBroadcast

	// ScopeChannelReadCharity allows app to read charity campaign details and user donations on the user's channel.
	ScopeChannelReadCharity

	// ScopeChannelEditCommercial allows app to run commercials on a channel.
	ScopeChannelEditCommercial

	// ScopeChannelReadEditors allows app to view a list of editors in a channel.
	ScopeChannelReadEditors

	// ScopeChannelManageExtensions allows app to manage a channel's Extension config, including activation Extensions.
	ScopeChannelManageExtensions

	// ScopeChannelReadGoals allows app to view Creator Goals for a channel.
	ScopeChannelReadGoals

	// ScopeChannelReadGuestStar allows app to read Guest Star details for the user's channel.
	ScopeChannelReadGuestStar

	// ScopeChannelManageGuestStar allows app to manage Guest Star for the user's channel.
	ScopeChannelManageGuestStar

	// ScopeChannelReadHypeTrain allows app to view Hype Train information for a channel.
	ScopeChannelReadHypeTrain

	// ScopeChannelManageModerators allows app to add and remove moderators on the user's channel.
	ScopeChannelManageModerators

	// ScopeChannelReadPolls allows app to view a channel's polls.
	ScopeChannelReadPolls

	// ScopeChannelManagePolls allows app to manage a channel's polls.
	ScopeChannelManagePolls

	// ScopeChannelReadPredictions allows app to view a channel's Channel Point Predictions.
	ScopeChannelReadPredictions

	// ScopeChannelManagePredictions allows app to manage a channel's Channel Point Predictions.
	ScopeChannelManagePredictions

	// ScopeChannelManageRaids allows app to manage a channel raiding another channel.
	ScopeChannelManageRaids

	// ScopeChannelReadRedemptions allows app to view Channel Points custom rewards and their redemptions on a channel.
	ScopeChannelReadRedemptions

	// ScopeChannelManageRedemptions allows app to manage Channel Points custom rewards and their redemptions on a channel.
	ScopeChannelManageRedemptions

	// ScopeChannelManageSchedule allows app to manage a channel's stream schedule.
	ScopeChannelManageSchedule

	// ScopeChannelReadStreamKey allows app to view an authorized user's stream key.
	ScopeChannelReadStreamKey

	// ScopeChannelReadSubscriptions allows app to view a list of all subscribers to a channel, and check if the user is
	// subscribed to a channel.
	ScopeChannelReadSubscriptions

	// ScopeChannelManageVideos allows app to manage a channel's videos, including deleting videos.
	ScopeChannelManageVideos

	// ScopeChannelReadVips allows app to view a list of VIPs in the user's channel.
	ScopeChannelReadVips

	// ScopeChannelManageVips allows app to add and remove VIPs in the user's channel.
	ScopeChannelManageVips

	// ScopeChannelModerate allows app to perform moderation actions in a channel.
	ScopeChannelModerate

	// ScopeClipsEdit allows app to manage Clips for a channel.
	ScopeClipsEdit

	// ScopeModerationRead allows app to view moderation data including Moderators, Bans, Timeouts, and
	// Automod settings for channels where the authenticated user is a moderator.
	ScopeModerationRead

	// ScopeModeratorManageAnnouncements allows app to send announcements in channels where the authenticated user
	// is a moderator.
	ScopeModeratorManageAnnouncements

	// ScopeModeratorManageAutomod allows app to manage messages held for review by AutoMod in channels where
	// the user is a moderator.
	ScopeModeratorManageAutomod

	// ScopeModeratorReadAutomodSettings allows app to view a broadcaster's AutoMod settings for channels where the
	// user is a moderator.
	ScopeModeratorReadAutomodSettings

	// ScopeModeratorManageAutomodSettings allows app to manage a broadcaster's AutoMod settings for channels where
	// the user is a moderator.
	ScopeModeratorManageAutomodSettings

	// ScopeModeratorReadBannedUsers allows app to view a list of bans and unbans for channels where the authenticated
	//user is a moderator.
	ScopeModeratorReadBannedUsers

	// ScopeModeratorManageBannedUsers allows app to ban and unban users in channels where the authenticated user is
	// a moderator.
	ScopeModeratorManageBannedUsers

	// ScopeModeratorReadBlockedTerms allows app to view a broadcaster's list of blocked terms.
	ScopeModeratorReadBlockedTerms

	// ScopeModeratorReadChatMessages allows app to read deleted chat messages in a channel.
	ScopeModeratorReadChatMessages

	// ScopeModeratorManageBlockedTerms allows app to manage a broadcaster's list of blocked terms.
	ScopeModeratorManageBlockedTerms

	// ScopeModeratorManageChatMessages allows app to delete chat messages in channels where the authenticated user
	// is a moderator.
	ScopeModeratorManageChatMessages

	// ScopeModeratorReadChatSettings allows app to view a broadcaster's chat room settings.
	ScopeModeratorReadChatSettings

	// ScopeModeratorManageChatSettings allows app to manage a broadcaster's chat room settings.
	ScopeModeratorManageChatSettings

	// ScopeModeratorReadChatters allows app to view the chatters in a broadcaster's chatroom.
	ScopeModeratorReadChatters

	// ScopeModeratorReadFollowers allows app to view the followers of a broadcaster.
	ScopeModeratorReadFollowers

	// ScopeModeratorReadGuestStar allows app to view Guest Star details for channels where the authenticated user
	// is a Guest Star moderator.
	ScopeModeratorReadGuestStar

	// ScopeModeratorManageGuestStar allows app to manage Guest Star details for channels where the authenticated
	// user is a Guest Star moderator.
	ScopeModeratorManageGuestStar

	// ScopeModeratorReadModerators allows app to view a list of moderators in channels where the authenticated
	// user is a moderator.
	ScopeModeratorReadModerators

	// ScopeModeratorReadShieldMode allows app to view a broadcaster's Shield Mode status.
	ScopeModeratorReadShieldMode

	// ScopeModeratorManageShieldMode allows app to manage a broadcaster's Shield Mode status.
	ScopeModeratorManageShieldMode

	// ScopeModeratorReadShoutouts allows app to view a broadcaster's shoutouts.
	ScopeModeratorReadShoutouts

	// ScopeModeratorManageShoutouts allows app to manage a broadcaster's shoutouts.
	ScopeModeratorManageShoutouts

	// ScopeModeratorReadSuspiciousUsers allows app to view chat messages from suspicious users and see users flagged
	// as suspicious in channels where the authenticated user is a moderator.
	ScopeModeratorReadSuspiciousUsers

	// ScopeModeratorReadUnbanRequests allows app to view a broadcaster's unban requests.
	ScopeModeratorReadUnbanRequests

	// ScopeModeratorManageUnbanRequests allows app to manage a broadcaster's unban requests.
	ScopeModeratorManageUnbanRequests

	// ScopeModeratorReadVips allows app to view the list of VIPs for channels where the authenticated user is
	// a moderator.
	ScopeModeratorReadVips

	// ScopeModeratorReadWarnings allows app to view warnings in channels where the authenticated user is a moderator.
	ScopeModeratorReadWarnings

	// ScopeModeratorManageWarnings allows app to warn users in channels where the authenticated user is a moderator.
	ScopeModeratorManageWarnings

	// ScopeUserBot allows app to join a chat channel as the authenticated user but appearing as a bot and perform
	// actions as the user.
	ScopeUserBot

	// ScopeUserEdit allows app to update the authenticated user's information.
	ScopeUserEdit

	// ScopeUserEditBroadcast allows app to view and edit the authenticated user's broadcasting config, including
	// Extension configs.
	ScopeUserEditBroadcast

	// ScopeUserReadBlockedUsers allows app to view the authenticated user's block list.
	ScopeUserReadBlockedUsers

	// ScopeUserManageBlockedUsers allows app to manage the authenticated user's block list.
	ScopeUserManageBlockedUsers

	// ScopeUserReadBroadcast allows app to view the authenticated user's broadcasting config, including
	// Extension configs.
	ScopeUserReadBroadcast

	// ScopeUserReadChat allows app to receive chatroom messages and informational notifications related to a
	// channel's chatroom.
	ScopeUserReadChat

	// ScopeUserManageChatColor allows app to update the color used for the authenticated user's name in chat.
	ScopeUserManageChatColor

	// ScopeUserReadEmail allows app to view the authenticated user's email address,
	ScopeUserReadEmail

	// ScopeUserReadEmotes allows app to view the emotes available to the authenticated user.
	ScopeUserReadEmotes

	// ScopeUserReadFollows allows app to view the list of channels that the authenticated user follows.
	ScopeUserReadFollows

	// ScopeUserReadModeratedChannels allows app to view the list of channels where the authenticated user is a
	// moderator.
	ScopeUserReadModeratedChannels

	// ScopeUserReadSubscriptions allows app to view the list of channels that the authenticated user is subscribed to.
	ScopeUserReadSubscriptions

	// ScopeUserReadWhispers allows app to receive whispers sent to the authenticated user.
	ScopeUserReadWhispers

	// ScopeUserManageWhispers allows app to receive whispers sent to the authenticated user, and send whispers on their
	// behalf.
	ScopeUserManageWhispers

	// ScopeUserWriteChat allows app to send chat messages as the authenticated user.
	ScopeUserWriteChat
)

func (*ScopeType) MarshalJSON added in v0.1.3

func (t *ScopeType) MarshalJSON() ([]byte, error)

func (*ScopeType) UnmarshalJSON added in v0.1.3

func (t *ScopeType) UnmarshalJSON(b []byte) error

type TokenResponse added in v0.1.4

type TokenResponse struct {
	TokenRequestStatus responseStatus
	TokenData          *AccessTokenRequestResponse
	FailureData        *FailedRequestResponse
}

TokenResponse stores the results of a token retrieval request.

type TokenRevocationResponse added in v0.1.4

type TokenRevocationResponse struct {
	RevocationStatus responseStatus
	FailureData      *FailedRequestResponse
}

TokenRevocationResponse stores the results of a token revocation request. A successful revocation request returns no details beyond a RevocationStatus of StatusSuccess.

func RevokeToken

func RevokeToken(clientId string, token string) (*TokenRevocationResponse, error)

RevokeToken revokes the supplied active bearer token.

type TokenValidationResponse added in v0.1.4

type TokenValidationResponse struct {
	ValidationStatus responseStatus
	ValidationData   *ValidTokenResponse
	FailureData      *FailedRequestResponse
}

TokenValidationResponse stores the results of a token validation request.

func ValidateToken

func ValidateToken(token string) (*TokenValidationResponse, error)

ValidateToken confirms, using the Twitch Helix API, whether the supplied bearer token is valid.

type ValidTokenResponse added in v0.1.3

type ValidTokenResponse struct {
	ClientId  string      `json:"client_id"`
	Login     string      `json:"login"`
	Scopes    []ScopeType `json:"scopes"`
	UserId    string      `json:"user_id"`
	ExpiresIn int         `json:"expires_in"`
}

ValidTokenResponse stores the parsed JSON response of a token validation request on a valid token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL