Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SLIM Framework Route Authentication v2 vs v3

I have an API built with Slim v2 and I secure certain routes passing a middleware function "authenticate":

    /**
     * List marca novos
     * method GET
     * url /novos/marca/:idmarca
     */
    $app->get('/novos/marca/:idmarca', 'authenticate', function($idmarca) {
        $response = array();
        $db = new DbHandler('dbnovos');


        // fetching marca
        $marca = $db->getMarcaNovos($idmarca);

        $response["error"] = false;
        $response["marca"] = array();

        array_walk_recursive($marca, function(&$val) {
            $val = utf8_encode((string)$val);
        });

        array_push($response["marca"], $marca);

        echoRespnse(200, $response, "marcaoutput");
    })->via('GET', 'POST');

The authenticate function checks if a headers Authorization value was sent (user_api_key) and checks it against the database.

I'm trying to get the same functionality in a Slim v3 API with the folowwing route:

    /**
     * List marca novos
     * method GET
     * url /novos/marca/:idmarca
     */
    $app->get('/novos/marca/{idmarca}', function ($request, $response, $args) {

    $output = array();
    $db = new DbHandler('mysql-localhost');
    $marca = $db->getMarcaNovos($args['idmarca']);

    if ($marca != NULL) {
        $i = 0;
        foreach($marca as $m) {
            $output[$i]["id"] = $m['id'];
            $output[$i]["nome"] = utf8_encode($m['nome']);
            $i++;
        }

    } else {
        // unknown error occurred
        $output['error'] = true;
        $output['message'] = "An error occurred. Please try again";
    }

    // Render marca view
    echoRespnse(200, $response, $output, "marca");
})->add($auth);

This is my middleware

/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
$auth = function ($request, $response, $next) {

$headers = $request->getHeaders();
$outcome = array();

// Verifying Authorization Header
if (isset($headers['Authorization'])) {
    $db = new DbHandler('mysql-localhost');

    // get the api key
    $api_key = $headers['Authorization'];
    // validating api key
    if (!$db->isValidApiKey($api_key)) {
        // api key is not present in users table
        $outcome["error"] = true;
        $outcome["message"] = "Access Denied. Invalid Api key";
        echoRespnse(401, $outcome, $output);
    } else {
        global $user_id;
        // get user primary key id
        $user_id = $db->getUserId($api_key);
        $response = $next($request, $response);
        return $response;
    }
} else {
    // api key is missing in header
    $outcome["error"] = true;
    $outcome["message"] = "Api key is missing";
    //echoRespnse(400, $response, $outcome);
    return $response->withStatus(401)->write("Not allowed here - ".$outcome["message"]);
}

};

But I always get the error: "Not allowed here - Api key is missing" Basically, the test if $headers['Authorization'] is set is failing. What is the $headers array structure or how do I get the Authorization value passed through the header?

like image 453
mjpramos Avatar asked Oct 30 '22 03:10

mjpramos


1 Answers

If you are sending something else than valid HTTP Basic Authorization header, PHP will not have access to it. You can work around this by adding the following rewrite rule to your .htaccess file.

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
like image 98
Mika Tuupola Avatar answered Nov 15 '22 07:11

Mika Tuupola