0

I am failing to create an Access Token for the Twillio Video Product with the golang SDK In the docs there is golang sadly not mentioned

Does anyone of you know how I can create the required access token?

The JWT package mentioned in the examples of the other languages can not be found in the Go SDK.

Simon Frey
  • 2,539
  • 2
  • 11
  • 20
  • This might help although this is quite old: https://www.youtube.com/watch?v=mTd3hHUy9OU, the api may have changed in the meantime. – Sazid Jun 04 '21 at 08:29

1 Answers1

2

I found that it is just not possible to do it with the default go SDK. I did follow the instructions on https://www.twilio.com/docs/iam/access-tokens and build the JWT myself. Maybe someone will find the solution handy:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/dvsekhvalnov/jose2go"
    "log"
    "time"
)

func main() {
    accountSid := "XXX"
    keySid := "YYY"
    keySecret := "ZZZ"

    username := "Simon"
    roomName := "SimonsRoom"

    now := time.Now()

    type JWTPayload struct {
        Jti                    string `json:"jti"`
        Issuer                 string `json:"iss"`
        Subject                string `json:"sub"`
        CreationUnixTimestamp  int64  `json:"iat"`
        NotBeforeUnixTimestamp int64  `json:"nbf"`
        ExpiresUnixTimestamp   int64  `json:"exp"`
        Grants                 struct {
            Identity string `json:"identity"`
            Video    struct {
                Room string `json:"room"`
            } `json:"video"`
        } `json:"grants"`
    }

    payload := JWTPayload{
        Jti:                    fmt.Sprintf("%s-%d",keySid,now.UnixNano()),
        Issuer:                 keySid,
        Subject:                accountSid,
        CreationUnixTimestamp:  now.Unix(),
        NotBeforeUnixTimestamp: now.Unix(),
        ExpiresUnixTimestamp:   now.Add(23*time.Hour).Unix(),
        Grants: struct {
            Identity string `json:"identity"`
            Video    struct {
                Room string `json:"room"`
            } `json:"video"`
        }{
            Identity: username,
            Video: struct {
                Room string `json:"room"`
            }{
                Room: roomName,
            },
        },
    }

    payloadByte, err := json.Marshal(payload)
    if err != nil {
        log.Fatal(err)
    }
    token, err := jose.SignBytes(payloadByte, jose.HS256, []byte(keySecret),
        jose.Header("cty", "twilio-fpa;v=1"),
        jose.Header("typ", "JWT"),
        jose.Header("alg", "HS256"),
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(token)
}
Simon Frey
  • 2,539
  • 2
  • 11
  • 20