diff --git a/README.md b/README.md index 2711af6..f1e43d5 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,10 @@ Each JSON configuration file for the gateways can specify detailed settings for ## Authentication Authentication can be enabled using the `--auth` flag. The auth token should be set through environment variables `GATEWAY_PASSWORD`. +Auth token needs to be the last entry in the RPC gateway URL. Example: + +`https://sample/rpc-gateway/sepolia/a1b2c3d4e5f7` + ### Running the Application To run the application with authentication: diff --git a/internal/auth/auth.go b/internal/auth/auth.go index ff13218..a6d18c5 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -2,17 +2,20 @@ package auth import ( "net/http" + "strings" ) func URLTokenAuth(token string) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authToken := r.URL.Query().Get("auth_token") - if authToken == "" || authToken != token { + pathParts := strings.Split(r.URL.Path, "/") + if len(pathParts) < 2 || pathParts[len(pathParts)-1] != token { w.WriteHeader(http.StatusUnauthorized) return } + // Remove the token part from the path to forward the request to the next handler + r.URL.Path = strings.Join(pathParts[:len(pathParts)-1], "/") next.ServeHTTP(w, r) }) } diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index 1952e0c..82dc4dc 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -6,7 +6,7 @@ import ( "testing" ) -func TestUrlTokenAuth(t *testing.T) { +func TestURLTokenAuth(t *testing.T) { validToken := "valid_token" middleware := URLTokenAuth(validToken) @@ -17,17 +17,22 @@ func TestUrlTokenAuth(t *testing.T) { }{ { name: "Valid token", - url: "/?auth_token=valid_token", + url: "/some/path/valid_token", + expectedStatus: http.StatusOK, + }, + { + name: "Valid token", + url: "/some/really/long/path/valid_token", expectedStatus: http.StatusOK, }, { name: "Invalid token", - url: "/?auth_token=invalid_token", + url: "/some/path/invalid_token", expectedStatus: http.StatusUnauthorized, }, { name: "Missing token", - url: "/", + url: "/some/path/", expectedStatus: http.StatusUnauthorized, }, }