您好,登錄后才能下訂單哦!
在Symfony中實現JWT(JSON Web Token)認證,你可以使用一個流行的庫,如lexik/jwt-authentication-bundle
。以下是如何在Symfony項目中設置和使用JWT認證的步驟:
首先,你需要安裝lexik/jwt-authentication-bundle
和firebase/php-jwt
庫。你可以使用Composer來安裝這些依賴:
composer require lexik/jwt-authentication-bundle
composer require firebase/php-jwt
接下來,你需要在你的Symfony項目中配置LexikJWTAuthenticationBundle
。打開你的config/packages/lexik_jwt_authentication.yaml
文件,并進行相應的配置:
lexik_jwt_authentication:
secret: '%env(JWT_SECRET)%'
algorithm: HS256
time_between_tokens_validations: 0
播放_refresh_token: true
refresh_token_ttl: 2592000
push_notification_payload: { "typ": "JWT", "alg": "HS256" }
challenge_on_token_not_valid: true
token_listener:
path: /api/login
methods: ['POST']
jwt_provider:
service: app.jwt_provider
success_handler: app.security.authentication.success_handler
failure_handler: app.security.authentication.failure_handler
authentication_manager: '@security.authentication_manager'
app.jwt_provider:
service: app.jwt_provider.service
jwt_secret: '%env(JWT_SECRET)%'
issuer: '%env(JWT_ISSUER)%'
audience: '%env(JWT_AUDIENCE)%'
app.security.authentication.success_handler:
class: App\Security\Authentication\SuccessHandler
app.security.authentication.failure_handler:
class: App\Security\Authentication\FailureHandler
你需要創建一些服務來處理JWT的生成和驗證。在你的src/Service
目錄下創建以下服務:
mkdir -p src/Service/JWT
touch src/Service/JWT/JwtProvider.php src/Service/JWT/TokenEncoder.php
namespace App\Service\JWT;
use Lexik\JWTAuthenticationBundle\Services\JWTAuthenticationManager;
use Firebase\JWT\JWT;
class JwtProvider
{
protected $jwtManager;
protected $encoder;
public function __construct(JWTAuthenticationManager $jwtManager, $encoder)
{
$this->jwtManager = $jwtManager;
$this->encoder = $encoder;
}
public function createToken($user)
{
$payload = [
'iss' => $_SERVER['HTTP_HOST'],
'iat' => time(),
'nbf' => time() + 10,
'exp' => time() + 3600,
'sub' => $user->getUsername(),
'username' => $user->getUsername(),
'roles' => $user->getRoles(),
];
return $this->encoder->encode($payload, $this->jwtManager->getSecret());
}
public function validateToken($token)
{
try {
$decoded = JWT::decode($token, $this->jwtManager->getSecret(), ['HS256']);
return $decoded;
} catch (\Exception $e) {
return null;
}
}
}
namespace App\Service\JWT;
use Symfony\Component\Security\Core\Encoder\EncoderInterface;
class TokenEncoder implements EncoderInterface
{
public function encode($value)
{
return $value;
}
public function decode($value)
{
return json_decode($value, true);
}
public function isPasswordValid($value)
{
return true;
}
}
在你的控制器中,你可以使用JWT來保護路由。例如:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class ApiController extends AbstractController
{
/**
* @Route("/api/login", methods={"POST"})
*/
public function login(Request $request): JsonResponse
{
// 這里應該有用戶登錄邏輯
$user = $this->getUser(); // 假設你已經有了用戶對象
if (!$user) {
return new JsonResponse(['error' => 'Invalid credentials'], 401);
}
$token = $this->get('app.jwt_provider')->createToken($user);
return new JsonResponse(['token' => $token]);
}
/**
* @Route("/api/protected", methods={"GET"})
*/
public function protectedAction(Request $request): JsonResponse
{
$token = $request->headers->get('Authorization');
if (!$token) {
return new JsonResponse(['error' => 'Token not provided'], 401);
}
$decoded = $this->get('app.jwt_provider')->validateToken($token);
if (!$decoded) {
return new JsonResponse(['error' => 'Invalid token'], 401);
}
return new JsonResponse(['message' => 'Protected resource accessed successfully', 'user' => $decoded]);
}
}
最后,確保你的安全配置允許JWT認證。在你的config/packages/security.yaml
文件中添加JWT相關的配置:
security:
# ...
firewalls:
api:
pattern: ^/api
stateless: true
anonymous: false
jwt_provider: app.jwt_provider
access_control:
- { path: ^/api/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/, roles: IS_AUTHENTICATED_FULLY }
這樣,你就完成了在Symfony中實現JWT認證的基本步驟。你可以根據需要進一步擴展和定制這個流程。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。