From 5bbae63e6c96d40c2d929546ca4e108de7bf53a4 Mon Sep 17 00:00:00 2001 From: Fabian Vowie Date: Thu, 20 Jan 2022 21:22:06 +0100 Subject: [PATCH] Require 'Bearer' prefix in authorization header --- auth/authorization.go | 7 +++++-- auth/authorization_test.go | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/auth/authorization.go b/auth/authorization.go index 5e058eb..42f955f 100644 --- a/auth/authorization.go +++ b/auth/authorization.go @@ -1,6 +1,9 @@ package auth -import "net/http" +import ( + "net/http" + "strings" +) type AuthenticationMiddleware struct { Secret string @@ -10,7 +13,7 @@ func (middleware AuthenticationMiddleware) Middleware(next http.Handler) http.Ha return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authToken := r.Header.Get("Authorization") - if authToken == "" || authToken != middleware.Secret { + if authToken == "" || strings.HasPrefix(authToken, "Bearer ") == false || authToken[7:] != middleware.Secret { http.Error(w, "Forbidden", http.StatusForbidden) } else { next.ServeHTTP(w, r) diff --git a/auth/authorization_test.go b/auth/authorization_test.go index 7f8d45e..0aa737e 100644 --- a/auth/authorization_test.go +++ b/auth/authorization_test.go @@ -43,7 +43,7 @@ func TestAuthorizationMiddleware(t *testing.T) { middlewareHandler := middleware.Middleware(handler) request, _ := http.NewRequest("GET", "/", nil) - request.Header.Set("Authorization", token) + request.Header.Set("Authorization", "Bearer "+token) responseRecorder := httptest.NewRecorder() middlewareHandler.ServeHTTP(responseRecorder, request)