From 69740c3510a3f166bc7c7a3d44d98aa4c4398c45 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 16 Dec 2019 19:52:32 +0200 Subject: Change: fetch JWT access token from IDP, print it --- ickadmin.go | 52 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/ickadmin.go b/ickadmin.go index c6593a5..945ce9a 100644 --- a/ickadmin.go +++ b/ickadmin.go @@ -3,34 +3,62 @@ package main import ( "flag" "fmt" - "io/ioutil" + "github.com/go-ini/ini" "net/http" + "io/ioutil" "os" + "net/url" + "strings" + "strconv" + "encoding/json" ) +type jwt struct { + Scope string + Access_token string +} + func main() { - var url string + var config string - flag.StringVar(&url, "url", "", "what URL to retrieve?") + flag.StringVar(&config, "config", "", "what config file to read?") flag.Parse() - if url == "" { - fmt.Fprintf(os.Stderr, "MUST give URL\n") + if config == "" { + fmt.Fprintf(os.Stderr, "MUST give config file\n") os.Exit(1) } - resp, err := http.Get(url) + cfg, err := ini.Load(config) if err != nil { - fmt.Fprintf(os.Stderr, "fetch: %v\n", err) + fmt.Fprintf(os.Stderr, "reading %s: %v\n", config, err) os.Exit(1) } - b, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err) + idp := cfg.Section("").Key("idp").String() + id := cfg.Section("").Key("id").String() + secret := cfg.Section("").Key("secret").String() + + data := url.Values{} + data.Add("grant_type", "client_credentials") + data.Add("scope", "uapi_projects_get") + + client := &http.Client{} + req, err := http.NewRequest("POST", idp, strings.NewReader(data.Encode())) + req.SetBasicAuth(id, secret) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode()))) + + resp, err := client.Do(req) + if err != nil{ + fmt.Fprintf(os.Stderr, "POST %s: %v\n", idp, err) os.Exit(1) } - fmt.Printf("%s", b) + bodyText, err := ioutil.ReadAll(resp.Body) + s := string(bodyText) + + res := jwt{} + json.Unmarshal([]byte(s), &res) + fmt.Fprintf(os.Stdout, "%s\n", res.Access_token) } -- cgit v1.2.1