Add bearer token authentication
In this commit, we've added the capability to authenticate via bearer token to Meteologix's HTTP client. A new method "WithBearerToken" has been implemented, allowing a bearer token to be set in 'meteologix.go'. Additionally, in 'httpclient.go', the token is attached to the "Authorization" header for API requests. Tests asserting token setting functionality have been added in 'meteologix_test.go'. These changes open up an alternative authentication option for our API users. The bearer auth is not public yet, so there is no way for us to test this auth
This commit is contained in:
parent
173c6eb8ec
commit
a5667bb828
|
@ -133,6 +133,10 @@ func (hc *HTTPClient) setAuthentication(hr *http.Request) {
|
|||
hr.Header.Set("X-API-Key", hc.Config.apiKey)
|
||||
return
|
||||
}
|
||||
if hc.bearerToken != "" {
|
||||
hr.Header.Set("Authorization", "Bearer"+hc.bearerToken)
|
||||
return
|
||||
}
|
||||
if hc.authUser != "" && hc.authPass != "" {
|
||||
hr.SetBasicAuth(url.QueryEscape(hc.authUser), url.QueryEscape(hc.authPass))
|
||||
}
|
||||
|
|
|
@ -46,6 +46,8 @@ type Config struct {
|
|||
authPass string
|
||||
// authUser holds the (optional) username for the API user authentication
|
||||
authUser string
|
||||
// bearerToken holds the (optional) bearer token for the API authentication
|
||||
bearerToken string
|
||||
// userAgent represents an alternative User-Agent HTTP header string
|
||||
userAgent string
|
||||
}
|
||||
|
@ -97,6 +99,17 @@ func WithAPIKey(k string) Option {
|
|||
}
|
||||
}
|
||||
|
||||
// WithBearerToken uses a bearer token for the client authentication of the
|
||||
// HTTP client
|
||||
func WithBearerToken(t string) Option {
|
||||
if t == "" {
|
||||
return nil
|
||||
}
|
||||
return func(co *Config) {
|
||||
co.bearerToken = t
|
||||
}
|
||||
}
|
||||
|
||||
// WithPassword sets the HTTP Basic auth authPass for the HTTP client
|
||||
func WithPassword(p string) Option {
|
||||
if p == "" {
|
||||
|
|
|
@ -66,6 +66,28 @@ func TestNew_WithAPIKey(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestNew_WithBearerToken(t *testing.T) {
|
||||
e := "BEARER-TOKEN"
|
||||
c := New(WithBearerToken(e))
|
||||
if c == nil {
|
||||
t.Errorf("NewWithBearerToken failed, expected Client, got nil")
|
||||
return
|
||||
}
|
||||
if c.config.bearerToken != e {
|
||||
t.Errorf("NewWithBearerToken failed, expected token value: %s, got: %s", e,
|
||||
c.config.bearerToken)
|
||||
}
|
||||
c = New(WithBearerToken(""))
|
||||
if c == nil {
|
||||
t.Errorf("NewWithBearerToken failed, expected Client, got nil")
|
||||
return
|
||||
}
|
||||
if c.config.bearerToken != "" {
|
||||
t.Errorf("NewWithBearerToken failed, expected empty token, got: %s",
|
||||
c.config.bearerToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew_WithUsername(t *testing.T) {
|
||||
e := "username"
|
||||
c := New(WithUsername(e))
|
||||
|
|
Loading…
Reference in a new issue