forked from FabianVowie/Lithium
Browse Source
Merge commit '6ac87dc7dcdf4d3be4a40f7ab19b46ffc1a8cf2f' into HEAD
feature/update-route-registration
Merge commit '6ac87dc7dcdf4d3be4a40f7ab19b46ffc1a8cf2f' into HEAD
feature/update-route-registration
Jenkins
3 years ago
committed by
Fabian Vowie
No known key found for this signature in database
GPG Key ID: C27317C33B27C410
3 changed files with 82 additions and 2 deletions
@ -0,0 +1,28 @@ |
|||
package auth |
|||
|
|||
import ( |
|||
"net/http" |
|||
"strings" |
|||
) |
|||
|
|||
type AuthenticationMiddleware struct { |
|||
secret string |
|||
} |
|||
|
|||
func (middleware AuthenticationMiddleware) Middleware(next http.Handler) http.Handler { |
|||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
|||
authToken := r.Header.Get("Authorization") |
|||
|
|||
if authToken == "" || strings.HasPrefix(authToken, "Bearer ") == false || authToken[7:] != middleware.secret { |
|||
http.Error(w, "Forbidden", http.StatusForbidden) |
|||
} else { |
|||
next.ServeHTTP(w, r) |
|||
} |
|||
}) |
|||
} |
|||
|
|||
func CreateAuthenticationMiddleware(secret string) AuthenticationMiddleware { |
|||
return AuthenticationMiddleware{ |
|||
secret: secret, |
|||
} |
|||
} |
@ -0,0 +1,40 @@ |
|||
package auth |
|||
|
|||
import ( |
|||
"net/http" |
|||
"net/http/httptest" |
|||
"testing" |
|||
|
|||
"github.com/bxcodec/faker/v3" |
|||
"github.com/stretchr/testify/assert" |
|||
) |
|||
|
|||
func TestAuthorizationMiddleware(t *testing.T) { |
|||
token := faker.Word() |
|||
middleware := CreateAuthenticationMiddleware(token) |
|||
|
|||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
|||
w.WriteHeader(http.StatusOK) |
|||
}) |
|||
|
|||
middlewareHandler := middleware.Middleware(handler) |
|||
|
|||
t.Run("AuthorizationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) { |
|||
request, _ := http.NewRequest("GET", "/", nil) |
|||
responseRecorder := httptest.NewRecorder() |
|||
|
|||
middlewareHandler.ServeHTTP(responseRecorder, request) |
|||
|
|||
assert.Equal(t, 403, responseRecorder.Code) |
|||
}) |
|||
|
|||
t.Run("AuthorizationMiddleware continues when authorization header is correct", func(t *testing.T) { |
|||
request, _ := http.NewRequest("GET", "/", nil) |
|||
request.Header.Set("Authorization", "Bearer "+token) |
|||
responseRecorder := httptest.NewRecorder() |
|||
|
|||
middlewareHandler.ServeHTTP(responseRecorder, request) |
|||
|
|||
assert.Equal(t, 200, responseRecorder.Code) |
|||
}) |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue