[core] Implement bearer token authentication (#3043)

This commit is contained in:
Eugene Molotov 2022-10-19 21:39:35 +05:00 committed by GitHub
parent 5b53e76477
commit d483bf2b81
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 1 deletions

View File

@ -57,7 +57,7 @@ by_bridge = false
[authentication] [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! ; 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. ; This default password is public knowledge. Replace it.
password = "7afbf648a369b261" password = "7afbf648a369b261"
; This will be used only for actions that require privileged access
access_token = ""
[error] [error]
; Defines how error messages are returned by RSS-Bridge ; Defines how error messages are returned by RSS-Bridge

View File

@ -0,0 +1,52 @@
<?php
/**
* This file is part of RSS-Bridge, a PHP project capable of generating RSS and
* Atom feeds for websites that don't have one.
*
* For the full license information, please view the UNLICENSE file distributed
* with this source code.
*
* @package Core
* @license http://unlicense.org/ UNLICENSE
* @link https://github.com/rss-bridge/rss-bridge
*/
final class ApiAuthenticationMiddleware
{
public function __invoke($request): void
{
$accessTokenInConfig = Configuration::getConfig('authentication', 'access_token');
if (!$accessTokenInConfig) {
$this->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);
}
}