我正在開發一個 API,并且我已經實作了一個 JWT 以使其無狀態。我創建了一個 AuthController,它在登錄資訊正確時回傳一個 JWT。在這里您可以看到生成令牌的回傳代碼:
/* RETURN MESSAGE */
$body = [
'auth_token' => $jwt,
];
$json = new JsonResponse($body);
$json->setStatusCode(201, "Created"); // Headers
return $json;
這是我運行身份驗證方法時的結果, un the URL localhost:8000/authenticate。
現在,我需要做的是,當用戶嘗試獲取另一個/URL 時,如果他沒有在請求的標頭中傳遞 Bearer 令牌,程式將不允許他訪問它。但它不起作用。該平臺始終允許我輸入任何 URL,而無需在標題中設定授權。
這是我的安全檔案,我嘗試在其中進行設定:
security:
# https://symfony.com/doc/current/security/authenticator_manager.html
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#c-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
encoders:
App\Entity\ATblUsers:
algorithm: bcrypt
providers:
users_in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
# Anonymous property is no longer supported by Symfony. It is commented by now, but it will be deleted in
# future revision:
# anonymous: true
guard:
authenticators:
- App\Security\JwtAuthenticator
lazy: true
provider: users_in_memory
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
stateless: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
最后,這是我的App\Security\JwtAuthenticator:
namespace App\Security;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Firebase\JWT\JWT;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
class JwtAuthenticator extends AbstractGuardAuthenticator
{
private $em;
private $params;
public function __construct(EntityManagerInterface $em, ContainerBagInterface $params)
{
$this->em = $em;
$this->params = $params;
}
public function start(Request $request, AuthenticationException $authException = null): JsonResponse
{
$body = [
'message' => 'Authentication Required',
];
return new JsonResponse($body, Response::HTTP_UNAUTHORIZED);
}
public function supports(Request $request): bool
{
return $request->headers->has('Authorization');
}
public function getCredentials(Request $request)
{
return $request->headers->get('Authorization');
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
try{
$credentials = str_replace('Bearer ', '', $credentials);
$jwt = (array) JWT::decode($credentials, $this->params->get('jwt_secret'), ['HS256']);
return $this->em->getRepository('App:ATblUsers')->find($jwt['sub']);
}catch (\Exception $exception){
throw new AuthenticationException($exception->getMessage());
}
}
public function checkCredentials($credentials, UserInterface $user)
{
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse
{
return new JsonResponse([
'message' => $exception->getMessage()
], Response::HTTP_UNAUTHORIZED);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)
{
return;
}
public function supportsRememberMe(): bool
{
return false;
}
}
我一直在查看很多網站和教程,但沒有人完全按照我的需要做或正在實作與我需要的不匹配的非常基本的功能。幾乎所有這些網站都使用 Symfony 4 解釋了這一點,但我使用的是 Symfony 5,因此不推薦使用教程中使用的許多功能。有人知道我錯過了什么嗎?
uj5u.com熱心網友回復:
您可能缺少以下access_control配置security.yaml:
security:
# https://symfony.com/doc/current/security/authenticator_manager.html
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#c-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
encoders:
App\Entity\ATblUsers:
algorithm: bcrypt
providers:
users_in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
# Anonymous property is no longer supported by Symfony. It is commented by now, but it will be deleted in
# future revision:
# anonymous: true
guard:
authenticators:
- App\Security\JwtAuthenticator
lazy: true
provider: users_in_memory
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
stateless: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/authenticate, roles: PUBLIC_ACCESS }
- { path: ^/, roles: IS_AUTHENTICATED_FULLY }
uj5u.com熱心網友回復:
我沒有詳細查看你的代碼,我只是想告訴你,你正在努力做的事情已經存在于一個維護和記錄良好的包中,你不需要硬編碼,我真的邀請你使用它非常有用。
https://github.com/lexik/LexikJWTAuthenticationBundle
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/331936.html
下一篇:集合型別新增元素關系null
