Browse Source

Require 'Bearer' prefix in authorization header

feature/add-authorization
Fabian Vowie 3 years ago
parent
commit
5bbae63e6c
No known key found for this signature in database GPG Key ID: C27317C33B27C410
  1. 7
      auth/authorization.go
  2. 2
      auth/authorization_test.go

7
auth/authorization.go

@ -1,6 +1,9 @@
package auth package auth
import "net/http"
import (
"net/http"
"strings"
)
type AuthenticationMiddleware struct { type AuthenticationMiddleware struct {
Secret string 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) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.Header.Get("Authorization") 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) http.Error(w, "Forbidden", http.StatusForbidden)
} else { } else {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)

2
auth/authorization_test.go

@ -43,7 +43,7 @@ func TestAuthorizationMiddleware(t *testing.T) {
middlewareHandler := middleware.Middleware(handler) middlewareHandler := middleware.Middleware(handler)
request, _ := http.NewRequest("GET", "/", nil) request, _ := http.NewRequest("GET", "/", nil)
request.Header.Set("Authorization", token)
request.Header.Set("Authorization", "Bearer "+token)
responseRecorder := httptest.NewRecorder() responseRecorder := httptest.NewRecorder()
middlewareHandler.ServeHTTP(responseRecorder, request) middlewareHandler.ServeHTTP(responseRecorder, request)

Loading…
Cancel
Save