Skip to content

Instantly share code, notes, and snippets.

@allenmichael
Created February 3, 2018 04:31
Show Gist options
  • Select an option

  • Save allenmichael/5aa87cfca7c2b1e59b585f2eb3f1b552 to your computer and use it in GitHub Desktop.

Select an option

Save allenmichael/5aa87cfca7c2b1e59b585f2eb3f1b552 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
jose "github.com/dvsekhvalnov/jose2go"
"github.com/dvsekhvalnov/jose2go/keys/rsa"
uuid "github.com/satori/go.uuid"
"github.com/spacemonkeygo/openssl"
)
const aud = "https://api.box.com/oauth2/token"
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
dat, err := ioutil.ReadFile("./config.json")
check(err)
var f interface{}
errJson := json.Unmarshal(dat, &f)
check(errJson)
m := f.(map[string]interface{})
bap := m["boxAppSettings"].(map[string]interface{})
bapap := bap["appAuth"].(map[string]interface{})
privateKey := []byte(bapap["privateKey"].(string))
passphrase := bapap["passphrase"].(string)
prive, err := openssl.LoadPrivateKeyFromPEMWithPassword(privateKey, passphrase)
check(err)
newKey, err := prive.MarshalPKCS1PrivateKeyPEM()
check(err)
newPrivateKey, e := Rsa.ReadPrivate(newKey)
check(e)
kid := bapap["publicKeyID"]
clientId := bap["clientID"]
clientSecret := bap["clientSecret"]
enterpriseId := m["enterpriseID"]
jti := uuid.Must(uuid.NewV4()).String()
expires := time.Now().Add(time.Duration(50) * time.Second).Unix()
payload := fmt.Sprintf(`{"iss": "%s","sub": "%s","box_sub_type": "enterprise","aud": "%s","jti": "%s","exp": %d}`, clientId, enterpriseId, aud, jti, expires)
fmt.Println(payload)
token, err := jose.Sign(payload, jose.RS256, newPrivateKey, jose.Headers(map[string]interface{}{"alg": "RS256", "kid": kid, "typ": "JWT"}))
check(err)
fmt.Println(token)
data := url.Values{}
data.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
data.Add("client_id", clientId.(string))
data.Add("client_secret", clientSecret.(string))
data.Add("assertion", token)
body := data.Encode()
resp, err := http.Post(aud, "application/x-www-form-urlencoded", strings.NewReader(body))
check(err)
defer resp.Body.Close()
fmt.Println(resp.Status)
bodyBytes, err := ioutil.ReadAll(resp.Body)
check(err)
bodyString := string(bodyBytes)
fmt.Println(bodyString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment