Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check header Authorization on Restler API framework

Tags:

rest

php

I want to extend Restler to check if a valid value of custom header Authorization was passed. I am having trouble in getting around the fix, I tried this, but no chance:

class AuthenticateMe implements iAuthenticate() {

function __isAuthenticated() {
    //return isset($_SERVER['HTTP_AUTH_KEY']) && $_SERVER['HTTP_AUTH_KEY']==AuthenticateMe::KEY ? TRUE : FALSE;
    $headers = apache_request_headers();
    foreach ($headers as $header => $value) {
        if($header == "Authorization") {
            return TRUE;
        } else {
            //return FALSE;
            throw new RestException(404);
        }
    }
}
}
like image 206
planet x Avatar asked Dec 05 '25 10:12

planet x


1 Answers

Let me quickly fix your custom auth header example

class HeaderAuth implements iAuthenticate{
    function __isAuthenticated(){
        //we are only looking for a custom header called 'Auth'
        //but $_SERVER prepends HTTP_ and makes it all uppercase
        //thats why we need to look for 'HTTP_AUTH' instead
        //also do not use header 'Authorization'. It is not
        //included in PHP's $_SERVER variable
        return isset($_SERVER['HTTP_AUTH']) && $_SERVER['HTTP_AUTH']=='password';
    }
}

I have tested it to make sure it works!

Here is how to make it work with Authorization header, it works only on apache servers

 class Authorization implements iAuthenticate{
    function __isAuthenticated(){
        $headers =  apache_request_headers();
        return isset($headers['Authorization']) && $headers['Authorization']=='password';
    }
}

I figured out that PHP converts Authorization header into $_SERVER['PHP_AUTH_DIGEST'] or $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] depending on the type of auth request (digest or basic), we can use the following .htaccess file to enable the $_SERVER['HTTP_AUTHORIZATION'] header

DirectoryIndex index.php

DirectoryIndex index.php
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ index.php [QSA,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]
    RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
</IfModule>

important part is RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

Now our example can be simplified to:

class Authorization implements iAuthenticate{
    function __isAuthenticated(){
        return isset($_SERVER['HTTP_AUTHORIZATION']) && $_SERVER['HTTP_AUTHORIZATION']=='password';
    }
}
like image 188
3 revsLuracast Avatar answered Dec 08 '25 00:12

3 revsLuracast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!