Symfony 4,如何基于JSON响应执行身份验证操作?
我(想)有一个主控制器来检查前端提供的API密钥是否正确,然后才执行一些操作。这是总控制员:Symfony 4,如何基于JSON响应执行身份验证操作?,symfony,symfony4,Symfony,Symfony4,我(想)有一个主控制器来检查前端提供的API密钥是否正确,然后才执行一些操作。这是总控制员: <?php namespace App\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; us
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class AuthenticationController extends AbstractController
{
/**
* @param Request $request
* @return JsonResponse
*/
public function checkAuthentication(Request $request)
{
if (empty($request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse(['success' => 'This is a valid API key, Authentication succeeded'], 200);
}
}
我目前的设置在提供的API密钥正确与否的两种情况下都有效,我理解为什么是这样,但是否有办法指定它只在成功的情况下有效?还是用另一种聪明的方式做同样的事情?我想到了一个变量,您可以根据情况将其设置为
1
,2
或3
,然后检查,但这是不可维护的,而且通常是一种不好的做法。控制器是否有责任对用户进行身份验证?控制器必须接收请求,然后给出响应,仅此而已
这是一个非常有用的案例资源使用身份验证保护对请求进行身份验证。不要在控制器中执行此类操作。@emix谢谢您的提示。我尝试用多种方式做事情,事实上,这可能不是最佳实践,但它只是我正在制作的一个学习应用程序。所以我肯定会接受你的建议,然后再做,但现在我正在尝试做不同的事情来提高我的问题解决技巧。我不认为你想做的是可能的。你可能会想点别的。谢谢你的链接,但是我没有在链接中读到任何对我有帮助的东西。
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Controller\AuthenticationController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
class SomeEntityController extends AbstractController
{
private $entityManager;
/**
* ApiKeyAuthenticatorService constructor.
* @param EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @Route("/Some/Uri", methods={"GET"})
* @param AuthenticationController $apiKeyAuthenticator
* @param Request $request
* @return JsonResponse
*/
public function AuthenticateAPI(AuthenticationController $apiKeyAuthenticator, Request $request)
{
$AuthenticatorObject = $apiKeyAuthenticator->checkAuthentication($request);
if($AuthenticatorObject){ //what to do here?
return new JsonResponse($this->entityManager->getRepository('App\Entity\SomeEntity')->findAll());
}
return $AuthenticatorObject;
}
}