我开始使用Codeigniter 4 Shield。
我将这段代码添加到了app/Config/Routes.php
文件中。
$routes->get('/access/token', static function() {
$token = auth()->user()->generateAccessToken(service('request')->getVar('token_name'));
return json_encode(['token' => $token->raw_token]);
});
当我尝试使用URL https://example.com/access/token
在Web浏览器中访问路由时,出现错误:
Call to a member function generateAccessToken() on null
由以下代码行生成:
$token = auth()->user()->generateAccessToken(service('request')->getVar('token_name'));
背景信息:
- 我已经使用Composer安装了Codeigniter 4 Shield,运行了相应的数据库迁移,其他一切都运行良好。
- 我的Codeigniter 4盾 “登录” 和 “注册” 页面工作正常。
- 如何在
app/Config/Routes.php
文件中自动加载generateAccessToken()
?*
1条答案
按热度按时间3qpi33ja1#
您需要提交登录凭据(电子邮件和密码)沿着HTTP
POST
请求,以帮助识别请求访问令牌的用户。否则,auth()->user()
为空,因此出现错误。要生成访问令牌,您需要首先对用户进行身份验证。
例如:(使用
email
和password
)1.定义您的 “访问令牌” 路由。注意使用
->post(...)
而不是->get(...)
。1.定义将处理 “访问令牌” 生成的Controller方法。Issuing the Tokens
1.使用
app/Config/Filters.php
上的$filters
设置保护您的/api
路由。Protecting Routes"session"
和"toolbar"
筛选器中排除您的 “访问令牌”("auth/token"
)路由以及所有API路由("api/*"
)。1.向
auth/token
路由发出一次初始HTTPPOST
请求,以接收 “访问令牌”。接收到令牌后,将其存储在客户端中。即:在localStorage中1.现在,您可以使用
Authorization
标头发送接收/存储的访问令牌沿着应用程序中所有其他受保护的API HTTP请求,而无需重新验证用户。例如: