您好,登錄后才能下訂單哦!
在Symfony中實(shí)現(xiàn)JWT(JSON Web Token)認(rèn)證,你可以使用一個(gè)流行的庫(kù),如lexik/jwt-authentication-bundle
。以下是如何在Symfony項(xiàng)目中設(shè)置和使用JWT認(rèn)證的步驟:
首先,你需要安裝lexik/jwt-authentication-bundle
和firebase/php-jwt
庫(kù)。你可以使用Composer來(lái)安裝這些依賴:
composer require lexik/jwt-authentication-bundle
composer require firebase/php-jwt
接下來(lái),你需要在你的Symfony項(xiàng)目中配置LexikJWTAuthenticationBundle
。打開(kāi)你的config/packages/lexik_jwt_authentication.yaml
文件,并進(jìn)行相應(yīng)的配置:
lexik_jwt_authentication:
secret: '%env(JWT_SECRET)%'
algorithm: HS256
time_between_tokens_validations: 0
播放_(tái)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
你需要?jiǎng)?chuàng)建一些服務(wù)來(lái)處理JWT的生成和驗(yàn)證。在你的src/Service
目錄下創(chuàng)建以下服務(wù):
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來(lái)保護(hù)路由。例如:
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
{
// 這里應(yīng)該有用戶登錄邏輯
$user = $this->getUser(); // 假設(shè)你已經(jīng)有了用戶對(duì)象
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認(rèn)證。在你的config/packages/security.yaml
文件中添加JWT相關(guān)的配置:
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中實(shí)現(xiàn)JWT認(rèn)證的基本步驟。你可以根據(jù)需要進(jìn)一步擴(kuò)展和定制這個(gè)流程。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。