Search code examples
phpajaxauthenticationbasic-authenticationslim

Basic auth with Slim no response


I am implementing a basic auth with Slim and REST. I have installed the basic auth via Composer and used the below code.

<?php

require 'confing.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim;

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/admin", /* or ["/admin", "/api"] */
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "user" => "passw0rd"
    ],
    "callback" => function ($request, $response, $arguments) {
        print_r($arguments);
    }
]));

$app->get('/getLaboorState/:laboor_id', function($laboor_id) use ($app) {
    $db =getDB();

    $sql="SELECT status FROM laboor WHERE laboor_id='".$laboor_id."'";
    $stmt = $db->query($sql); 
    $items = $stmt->fetchAll();
    echo json_encode($items);


});

$app->run();
?>

When I am trying now to connect the /getLaboorState with Postman it returns nothing. I used same username and password in postman and nothing shows, but when I take the basic auth it works fine.

Other questions is, after implement the basic auth, how can I restrict all slim api to go throw each api before run the query?

This is a pic from Postman:

Note: then I want to use the API with AJAX.


Solution

  • you need to use $authenticate($app) to restrict all slim api to go throw each api before run the query

    $app->get('/profile(/)(:id)', $authenticate($app), function($laboor_id) use ($app) {
    //Your logic here
    })->name('profile');
    
    $authenticate = function ($app) {
        return function () use ($app) {
    //your logic here
            if (!isset($_SESSION['ID'])) {
    
                $app->redirect($app->urlFor('loginpage'));
    
            }
       };
    };
    

    Use bellow code to display the exact error coming while calling Ajax request

    header('Access-Control-Allow-Origin: *');
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
    

    Hope this helps, Accept the answer if it works.. or comment