您好,登录后才能下订单哦!
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。