From 43a3357473c688b050985175c6148da76ec173a2 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Tue, 17 Oct 2017 18:01:26 -0700 Subject: [PATCH] svchost/auth: token-based HostCredentials This is the only credentials type we support right now, which just sends an opaque token via the "Bearer" HTTP auth scheme. --- svchost/auth/token_credentials.go | 20 ++++++++++++++++++++ svchost/auth/token_credentials_test.go | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 svchost/auth/token_credentials.go create mode 100644 svchost/auth/token_credentials_test.go diff --git a/svchost/auth/token_credentials.go b/svchost/auth/token_credentials.go new file mode 100644 index 0000000000..8f771b0d9b --- /dev/null +++ b/svchost/auth/token_credentials.go @@ -0,0 +1,20 @@ +package auth + +import ( + "net/http" +) + +// HostCredentialsToken is a HostCredentials implementation that represents a +// single "bearer token", to be sent to the server via an Authorization header +// with the auth type set to "Bearer" +type HostCredentialsToken string + +// PrepareRequest alters the given HTTP request by setting its Authorization +// header to the string "Bearer " followed by the encapsulated authentication +// token. +func (tc HostCredentialsToken) PrepareRequest(req *http.Request) { + if req.Header == nil { + req.Header = http.Header{} + } + req.Header.Set("Authorization", "Bearer "+string(tc)) +} diff --git a/svchost/auth/token_credentials_test.go b/svchost/auth/token_credentials_test.go new file mode 100644 index 0000000000..3f7355063e --- /dev/null +++ b/svchost/auth/token_credentials_test.go @@ -0,0 +1,18 @@ +package auth + +import ( + "net/http" + "testing" +) + +func TestHostCredentialsToken(t *testing.T) { + creds := HostCredentialsToken("foo-bar") + req := &http.Request{} + + creds.PrepareRequest(req) + + authStr := req.Header.Get("authorization") + if got, want := authStr, "Bearer foo-bar"; got != want { + t.Errorf("wrong Authorization header value %q; want %q", got, want) + } +}