您好我在lynda的课程中使用Slim创建了一个Web服务"在PHP中使用Slim Micro Framework构建API"但是当我想登录时,会发生此错误
注意:第12行的C:\ wamp64 \ www \ lynda2 \ src \ Chatter \ Middleware \ Authentication.php中未定义的偏移量为0
验证
namespace Chatter\Middleware;
use Chatter\Models\User;
class Authentication
{
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = $auth[0];
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
$response->withStatus(401);
return $response;
}
$response = $next($request, $response);
return $response;
}
}
User.php
<pre><code>
namespace Chatter\Models;
class User extends \Illuminate\Database\Eloquent\Model
{
public function authenticate($apikey)
{
$user = User::where('apikey', '=', $apikey)->take(1)->get();
$this->details = $user[0];
return ($user[0]->exists) ? true : false;
}
}
</code></pre>
index.php
<pre><code>
require 'vendor/autoload.php';
include 'bootstrap.php';
use Chatter\Models\Message;
use Chatter\Middleware\Logging as ChatterLogging;
use Chatter\Middleware\Authentication as ChatterAuth;
$app = new \Slim\App();
$app->add(new ChatterAuth());
$app->add(new ChatterLogging());
$app->get('/messages', function ($request, $response, $args) {
$_message = new Message();
$messages = $_message->all();
$payload = [];
foreach($messages as $_msg) {
$payload[$_msg->id] = ['body' => $_msg->body, 'user_id' => $_msg->user_id, 'created_at' => $_msg->created_at];
}
return $response->withStatus(200)->withJson($payload);
});
$app->get('/', function ($request, $response, $args) {
return "This is a catch all route for the root that doesn't do anything useful.";
});
// Run app
$app->run();
</code></pre>
答案 0 :(得分:2)
错误表明当您&#34;登录&#34;没有授权标题。
$request->getHeader('Authorization')
返回一个空数组,因此当您尝试访问数组的第一个元素时,会出现错误:
$_apikey = $auth[0]; // Will trigger error, since there are no elements in the array
因此,要避免此错误,请按以下方式获取$apikey
:
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = array_shift($auth);
if ($_apikey) {
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
return $response->withStatus(401);
} else {
return $next($request, $response);
}
} else {
// Authorization header is missing, therefore unauthorized access
return $response->withStatus(401);
}
}
答案 1 :(得分:0)
这是一个较旧的线程,但万一其他人正在关注本教程...... OP 发布的代码应该完全按照它的功能执行 - 如果不存在授权标头,则会失败。 看起来 OP 错过了一步:将不记名令牌添加到请求中。在 Postman 中,转到 Authorization > Type > Bearer Token 并在输入字段中粘贴有效令牌。我相信它在教程中已经明确说明。之后,一切都按预期进行。