From 31475961a1b4c6e5396c981ac56e1a6cb53a61e2 Mon Sep 17 00:00:00 2001 From: andig Date: Thu, 14 May 2020 17:55:49 +0200 Subject: [PATCH] Support basic authorization (#149) --- README.md | 4 ++++ provider/http.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/README.md b/README.md index d326b5456e..262f04c456 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,10 @@ uri: https://volkszaehler/api/data/.json?from=now method: GET # default HTTP method headers: - content-type: application/json +auth: # basic authorization + type: basic + user: foo + password: bar insecure: false # set to true to trust self-signed certificates jq: .data.tuples[0][1] # parse response json scale: 0.001 # floating point factor applied to result, e.g. for kW to W conversion diff --git a/provider/http.go b/provider/http.go index d00c6e5d32..049e90acf2 100644 --- a/provider/http.go +++ b/provider/http.go @@ -2,6 +2,7 @@ package provider import ( "crypto/tls" + "encoding/base64" "fmt" "io" "math" @@ -25,6 +26,21 @@ type HTTP struct { jq *gojq.Query } +// Auth is the authorization config +type Auth struct { + Type, User, Password string +} + +// NewAuth creates authorization headers from config +func NewAuth(log *util.Logger, auth Auth, headers map[string]string) { + if strings.ToLower(auth.Type) != "basic" { + log.FATAL.Fatalf("config: unsupported auth type: %s", auth.Type) + } + + basicAuth := auth.User + ":" + auth.Password + headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(basicAuth)) +} + // NewHTTPProviderFromConfig creates a HTTP provider func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *HTTP { cc := struct { @@ -34,6 +50,7 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) * Jq string Scale float64 Insecure bool + Auth Auth }{} util.DecodeOther(log, other, &cc) @@ -49,6 +66,14 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) * scale: cc.Scale, } + // handle basic auth + if cc.Auth.Type != "" { + if p.headers == nil { + p.headers = make(map[string]string) + } + NewAuth(log, cc.Auth, p.headers) + } + // ignore the self signed certificate if cc.Insecure { customTransport := http.DefaultTransport.(*http.Transport).Clone()