From d483bf2b81b9fbb7738555da99c4a9e07f4c39e3 Mon Sep 17 00:00:00 2001 From: Eugene Molotov Date: Wed, 19 Oct 2022 21:39:35 +0500 Subject: [PATCH] [core] Implement bearer token authentication (#3043) --- config.default.ini.php | 5 ++- lib/ApiAuthenticationMiddleware.php | 52 +++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 lib/ApiAuthenticationMiddleware.php diff --git a/config.default.ini.php b/config.default.ini.php index 7ea40bc2..638a5ac9 100644 --- a/config.default.ini.php +++ b/config.default.ini.php @@ -57,7 +57,7 @@ by_bridge = false [authentication] -; Enables authentication for all requests to this RSS-Bridge instance. +; Enables basic authentication for all requests to this RSS-Bridge instance. ; ; Warning: You'll have to upgrade existing feeds after enabling this option! ; @@ -70,6 +70,9 @@ username = "admin" ; This default password is public knowledge. Replace it. password = "7afbf648a369b261" +; This will be used only for actions that require privileged access +access_token = "" + [error] ; Defines how error messages are returned by RSS-Bridge diff --git a/lib/ApiAuthenticationMiddleware.php b/lib/ApiAuthenticationMiddleware.php new file mode 100644 index 00000000..6a59e760 --- /dev/null +++ b/lib/ApiAuthenticationMiddleware.php @@ -0,0 +1,52 @@ +exit('Access token is not set in this instance', 403); + } + + if (isset($request['access_token'])) { + $accessTokenGiven = $request['access_token']; + } else { + $header = trim($_SERVER['HTTP_AUTHORIZATION'] ?? ''); + $position = strrpos($header, 'Bearer '); + + if ($position !== false) { + $accessTokenGiven = substr($header, $position + 7); + } else { + $accessTokenGiven = ''; + } + } + + if (!$accessTokenGiven) { + $this->exit('No access token given', 403); + } + + if ($accessTokenGiven != $accessTokenInConfig) { + $this->exit('Incorrect access token', 403); + } + } + + private function exit($message, $code) + { + http_response_code($code); + header('content-type: text/plain'); + die($message); + } +}