Skip to content

Commit

Permalink
Merge pull request #237 from go-openapi/issue-236
Browse files Browse the repository at this point in the history
detect the authorization header on params and default to it when present
  • Loading branch information
casualjim authored Mar 19, 2022
2 parents 753b551 + 97e6864 commit 6a17228
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 19 deletions.
4 changes: 2 additions & 2 deletions authinfo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ import (

func TestAuthInfoWriter(t *testing.T) {
hand := ClientAuthInfoWriterFunc(func(r ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam("authorization", "Bearer the-token-goes-here")
return r.SetHeaderParam(HeaderAuthorization, "Bearer the-token-goes-here")
})

tr := new(TestClientRequest)
err := hand.AuthenticateRequest(tr, nil)
assert.NoError(t, err)
assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get("Authorization"))
assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get(HeaderAuthorization))
}
4 changes: 2 additions & 2 deletions client/auth_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func init() {
func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return r.SetHeaderParam("Authorization", "Basic "+encoded)
return r.SetHeaderParam(runtime.HeaderAuthorization, "Basic "+encoded)
})
}

Expand All @@ -56,7 +56,7 @@ func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
// BearerToken provides a header based oauth2 bearer access token auth info writer
func BearerToken(token string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam("Authorization", "Bearer "+token)
return r.SetHeaderParam(runtime.HeaderAuthorization, "Bearer "+token)
})
}

Expand Down
5 changes: 3 additions & 2 deletions client/auth_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"net/http"
"testing"

"github.com/go-openapi/runtime"
"github.com/stretchr/testify/assert"
)

Expand All @@ -30,7 +31,7 @@ func TestBasicAuth(t *testing.T) {

req := new(http.Request)
req.Header = make(http.Header)
req.Header.Set("Authorization", r.header.Get("Authorization"))
req.Header.Set(runtime.HeaderAuthorization, r.header.Get(runtime.HeaderAuthorization))
usr, pw, ok := req.BasicAuth()
if assert.True(t, ok) {
assert.Equal(t, "someone", usr)
Expand Down Expand Up @@ -65,7 +66,7 @@ func TestBearerTokenAuth(t *testing.T) {
err := writer.AuthenticateRequest(r, nil)
assert.NoError(t, err)

assert.Equal(t, "Bearer the-shared-token", r.header.Get("Authorization"))
assert.Equal(t, "Bearer the-shared-token", r.header.Get(runtime.HeaderAuthorization))
}

func TestCompose(t *testing.T) {
Expand Down
7 changes: 6 additions & 1 deletion client/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,12 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
}

if auth == nil && r.DefaultAuthentication != nil {
auth = r.DefaultAuthentication
auth = runtime.ClientAuthInfoWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
if req.GetHeaderParams().Get(runtime.HeaderAuthorization) != "" {
return nil
}
return r.DefaultAuthentication.AuthenticateRequest(req, reg)
})
}
//if auth != nil {
// if err := auth.AuthenticateRequest(request, r.Formats); err != nil {
Expand Down
58 changes: 54 additions & 4 deletions client/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -717,8 +717,8 @@ func TestRuntime_AuthCanary(t *testing.T) {
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" {
rw.WriteHeader(401)
return
}
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
Expand Down Expand Up @@ -818,7 +818,7 @@ func TestRuntime_ContentTypeCanary(t *testing.T) {
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
return
}
Expand Down Expand Up @@ -870,7 +870,7 @@ func TestRuntime_ChunkedResponse(t *testing.T) {
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
return
}
Expand Down Expand Up @@ -1110,3 +1110,53 @@ func TestRuntime_FallbackConsumer(t *testing.T) {
assert.EqualValues(t, result, actual)
}
}

func TestRuntime_AuthHeaderParamDetected(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get(runtime.HeaderAuthorization) != "Bearer the-super-secret-token" {
rw.WriteHeader(401)
return
}
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()

rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return req.SetHeaderParam(runtime.HeaderAuthorization, "Bearer the-super-secret-token")
})

hu, _ := url.Parse(server.URL)

rt := New(hu.Host, "/", []string{"http"})
rt.DefaultAuthentication = BearerToken("not-the-super-secret-token")
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})

if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
2 changes: 2 additions & 0 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const (

// HeaderAccept the Accept header
HeaderAccept = "Accept"
// HeaderAuthorization the Authorization header
HeaderAuthorization = "Authorization"

charsetKey = "charset"

Expand Down
4 changes: 2 additions & 2 deletions security/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Aut
const prefix = "Bearer "
return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
var token string
hdr := r.Request.Header.Get("Authorization")
hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
if strings.HasPrefix(hdr, prefix) {
token = strings.TrimPrefix(hdr, prefix)
}
Expand Down Expand Up @@ -250,7 +250,7 @@ func BearerAuthCtx(name string, authenticate ScopedTokenAuthenticationCtx) runti
const prefix = "Bearer "
return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
var token string
hdr := r.Request.Header.Get("Authorization")
hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
if strings.HasPrefix(hdr, prefix) {
token = strings.TrimPrefix(hdr, prefix)
}
Expand Down
13 changes: 7 additions & 6 deletions security/bearer_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"testing"

"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/stretchr/testify/assert"
)

Expand All @@ -32,7 +33,7 @@ func TestValidBearerAuth(t *testing.T) {
assert.Equal(t, OAuth2SchemeName(req1), "owners_auth")

req2, _ := http.NewRequest("GET", "/blah", nil)
req2.Header.Set("Authorization", "Bearer token123")
req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
assert.True(t, ok)
Expand Down Expand Up @@ -76,7 +77,7 @@ func TestInvalidBearerAuth(t *testing.T) {
assert.Error(t, err)

req2, _ := http.NewRequest("GET", "/blah", nil)
req2.Header.Set("Authorization", "Bearer token124")
req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
assert.True(t, ok)
Expand Down Expand Up @@ -117,7 +118,7 @@ func TestMissingBearerAuth(t *testing.T) {
assert.NoError(t, err)

req2, _ := http.NewRequest("GET", "/blah", nil)
req2.Header.Set("Authorization", "Beare token123")
req2.Header.Set(runtime.HeaderAuthorization, "Beare token123")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
assert.False(t, ok)
Expand Down Expand Up @@ -170,7 +171,7 @@ func TestValidBearerAuthCtx(t *testing.T) {

req2, _ := http.NewRequest("GET", "/blah", nil)
req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
req2.Header.Set("Authorization", "Bearer token123")
req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
assert.True(t, ok)
Expand Down Expand Up @@ -229,7 +230,7 @@ func TestInvalidBearerAuthCtx(t *testing.T) {

req2, _ := http.NewRequest("GET", "/blah", nil)
req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
req2.Header.Set("Authorization", "Bearer token124")
req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
assert.True(t, ok)
Expand Down Expand Up @@ -284,7 +285,7 @@ func TestMissingBearerAuthCtx(t *testing.T) {
assert.Nil(t, req1.Context().Value(extra))

req2, _ := http.NewRequest("GET", "/blah", nil)
req2.Header.Set("Authorization", "Beare token123")
req2.Header.Set(runtime.HeaderAuthorization, "Beare token123")

ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
Expand Down

0 comments on commit 6a17228

Please sign in to comment.