1// Copyright 2015 go-swagger maintainers 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package middleware 16 17import ( 18 "net/http" 19 "net/http/httptest" 20 "testing" 21 22 "github.com/go-openapi/runtime/internal/testing/petstore" 23 "github.com/stretchr/testify/assert" 24) 25 26func TestSecurityMiddleware(t *testing.T) { 27 spec, api := petstore.NewAPI(t) 28 context := NewContext(spec, api, nil) 29 context.router = DefaultRouter(spec, context.api) 30 mw := newSecureAPI(context, http.HandlerFunc(terminator)) 31 32 recorder := httptest.NewRecorder() 33 request, _ := http.NewRequest("GET", "/api/pets", nil) 34 35 mw.ServeHTTP(recorder, request) 36 assert.Equal(t, 401, recorder.Code) 37 38 recorder = httptest.NewRecorder() 39 request, _ = http.NewRequest("GET", "/api/pets", nil) 40 request.SetBasicAuth("admin", "wrong") 41 42 mw.ServeHTTP(recorder, request) 43 assert.Equal(t, 401, recorder.Code) 44 assert.NotEmpty(t, recorder.Header().Get("WWW-Authenticate")) 45 46 recorder = httptest.NewRecorder() 47 request, _ = http.NewRequest("GET", "/api/pets", nil) 48 request.SetBasicAuth("admin", "admin") 49 50 mw.ServeHTTP(recorder, request) 51 assert.Equal(t, 200, recorder.Code) 52 53 recorder = httptest.NewRecorder() 54 request, _ = http.NewRequest("GET", "//apipets/1", nil) 55 56 mw.ServeHTTP(recorder, request) 57 assert.Equal(t, 200, recorder.Code) 58 59} 60