簡體   English   中英

帶有 SelfValidatingPassport 的 Symfony 6 ApiKeyAuthenticator 取代了警衛?

[英]Symfony 6 ApiKeyAuthenticator with SelfValidatingPassport replaces guard?

我使用 api-platform 將 symfony 5.1 api 遷移到 symfony 6。
我的應用程序有自己的用戶和密碼邏輯,與普通用戶數據庫不同,所以我必須創建我的 UserRepository 和 UserProvider。
我創建了一個具有登錄功能的控制器,用於檢查憑據並返回一個令牌。
symfony 5上,我實現了一個 AbstractGuardAuthenticator 來驗證令牌並加載用戶。
symfony 6上,我使用實現 AbstractAuthenticator 的新系統(個人意見:不如警衛清楚)。

security:
    enable_authenticator_manager: true
# [...]
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        api_user_provider:
            id: App\Security\UserProvider

    firewalls:
# [...]
        api:
            pattern: ^/api/
            stateless: true
            provider: api_user_provider
            custom_authenticators:
                - App\Security\TokenAuthenticator
<?php

namespace App\Security;

// usings

class TokenAuthenticator extends AbstractAuthenticator
{
// [...]
    public function supports(Request $request): ?bool
    {
        if ( $request->headers->has('Authorization') ) {
            return true;
        } else {
            throw new AuthenticationException('Authorization header is missing');
        }
    }

    public function authenticate(Request $request): Passport
    {
        $token = $this->getToken($request);
       
        return new SelfValidatingPassport(
            new UserBadge($token, function ($token): UserInterface {
                return $this->getUserFromToken($token);
            }), []
        );


    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return New JsonResponse(["result"=> "ok"]);
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse(["result" => "error"], Response::HTTP_UNAUTHORIZED);
    }


}

當我對需要登錄用戶的端點進行簡單調用時,例如:

GET http://localhost:8000/api/categories
Accept: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQi[...]

我期望一個類別列表,但我從onAuthenticationSuccess收到一個 json:

{"result":"ok"}

所以我認為我誤解了安全系統。 請幫我。
我做錯了什么?

這很簡單,你幾乎擁有它。 onAuthenticationSuccess必須返回 null 才能讓您的請求繼續。
返回 json: {"result": "ok"}時,您正在中斷您的原始請求。

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
     return null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM