[英]Jwt Token decode - Symfony 4
我正在嘗試解決與令牌請求相關的問題。 這是我在控制器中的 newArticle 函數(添加新文章):
public function newArticle(Request $request, EntityManagerInterface $entityManager): View
{
$data = json_decode($request->getContent(), true);
$title = $data['title'];
$content = $data['content'];
//$published_at = $data['published_at'];
$authorizationHeader = $request->headers->get('Authorization');
list(,$token) = explode(' ', $authorizationHeader);
$jwtToken = $this->JWTEncoder->decode($token);
$user_id = $data[$jwtToken];
$userId = $this->userRepository->findOneBy(['id' => $user_id['id']]);
$article = new Article();
$article->setTitle($title);
$article->setContent($content);
$article->setPublishedAt(new \DateTime());
$article->setUser($userId);
// Todo: 400 response - Invalid input
// Todo: 404 response - Response not found
// Incase our Post was a success we need to return a 201 HTTP CREATED response with the created object
if(in_array('ROLE_USER', $article->getUser()->getRoles(), true)) {
$entityManager->persist($article);
$entityManager->flush();
return View::create("You added an article successfully!", Response::HTTP_OK);
} else {
return View::create(["You are not a user! So please register to add an article!"], Response::HTTP_BAD_REQUEST);
}
}
在添加令牌標頭授權之前它正在工作,現在我收到此錯誤:
"error": {
"code": 500,
"message": "Internal Server Error",
"message": "Notice: Undefined offset: 1",
有人可以給我任何建議嗎?
我認為你的問題是這一行:
$user_id = $data[$jwtToken];
你應該重構它,認為它應該是這樣的:
$user_id = $data['user_id'];
或者
$user_id = $jwtToken['user_id'];
根據包含每個對象/數組的數據是您應該查找的位置。 首先,錯誤是為了調用數組上的偏移量,因此修復它應該沒問題(或者從日志中獲得更清晰的錯誤消息)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.