Luracast Restler Authentication

前端 未结 2 1707
不思量自难忘°
不思量自难忘° 2021-01-03 14:45

I’m using Luracast restler and i’m trying to implement some authentication by implementing iAuthenticate interface.

The thing is, my authentication code needs to qu

2条回答
  •  佛祖请我去吃肉
    2021-01-03 15:30

    Using Single DB Connection for your API and Authentication Classes

    Create a php file called config.php and place all your db information along with db connection and selection.

    For example

    Include this function using require_once on both Authentication class and API class, something like (for simplicity I'm not encrypting the password here)

    0){
                    self::$currentUser = $user;
                    return TRUE;
                }
            }
            header('WWW-Authenticate: Basic realm="'.self::REALM.'"');
            throw new RestException(401, 'Basic Authentication Required');
        }
    }
    

    Your API class can have a protected method that query the same db, it can be a different table that return the data using the same connection. For simplicity sake I use the same table here.

    Using require_once makes sure that the php file is included only once on the first encounter. Even if we stop using the auth class latter our api will keep functioning

    Assuming that following SQL is used to create our db table

    --
    -- Database: `mysql_db`
    --
    
    --
    -- Table structure for table `login`
    --
    
    CREATE TABLE IF NOT EXISTS `login` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `logged` datetime DEFAULT NULL,
      `user` varchar(10) DEFAULT NULL,
      `pass` varchar(10) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
    
    --
    -- Dumping data for table `login`
    --
    
    INSERT INTO `login` (`id`, `logged`, `user`, `pass`) VALUES
    (1, '2011-11-01 22:50:05', 'arul', 'mypass'),
    (2, '2011-11-01 23:43:25', 'paulo', 'hispass');
    

    And the index.php with the following

    addAPIClass('Simple','');
    $r->addAuthenticationClass('BasicAuthentication');
    $r->handle();
    

    The Result

    if you open index.php/restricted in the browser and key in the right username and password combination, you will see the following as the result :)

    [
      {
        "id": "1",
        "logged": "2011-11-01 22:50:05",
        "user": "arul",
        "pass": "mypass"
      },
      {
        "id": "2",
        "logged": "2011-11-01 23:43:25",
        "user": "paulo",
        "pass": "hispass"
      }
    ]
    

提交回复
热议问题