簡體   English   中英

Symfony 2.8 Guard AbstractGuardAuthenticator,如何返回真實令牌?

[英]Symfony 2.8 Guard AbstractGuardAuthenticator, how to return a real token?

我正在使用Symfony 2.8中新增的相對較新的Guard子系統中的AbstractGuardAuthenticator

我的設置非常簡單。 我將請求發送到受保護的URL,該URL采用用戶名:密碼base64編碼。 它會針對數據庫進行檢查,並應返回一個令牌。

認證成功的方法:

 public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        //If login successful, return token
        return new Response($this->tokenStorage->getToken());        
    }

它返回的是:

 PostAuthenticationGuardToken(user="test", authenticated=true, roles="ROLE_ADVANCED,
 ROLE_USER")

現在,考慮到AbstractGuardAuthenticator完全像這樣定義創建此令牌的方法,這就是我所期望的。

public function createAuthenticatedToken(UserInterface $user, $providerKey)
    {
        return new PostAuthenticationGuardToken(
            $user,
            $providerKey,
            $user->getRoles()
        );
    }

更新1.1:

現在,我使用LexikJWTAuthenticationBundle嘗試在應用程序的AbstractGuardAuthenticator中實現Json Web令牌。 Lexik捆綁包提供成功和失敗處理程序: lexik_jwt_authentication.handler.authentication_successlexik_jwt_authentication.handler.authentication_failure指向指向將某些JWT變量注入到其中的類。 如何將它們掛接到AbstractGuardAuthenticator的成功和失敗處理程序中?

 crud:
         anonymous: ~
         guard:
             authenticators:
                - app.token_authenticator
         pattern: ^/database/

Guard成敗的方法

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    if ($token = $request->headers->get('X-AUTH-TOKEN')) {
        //on success, let the request continue
    } else {
        //If login successful, return token
        return new Response($this->tokenStorage->getToken());
    }
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, 403);
}

我目前正在擴展JWTTokenAuthenticator與我自己的令牌認證器(而不是AbstractGuardAuthenticator合並,因為兩者都實現了GuardAuthenticatorInterface

我想知道如何返回真實的令牌,該令牌可用於驗證用戶身份,而不是每次都發送username:password。

Symfony Guard組件

Guard旨在簡化身份驗證子系統。

在加入Guard之前,設置自定義身份驗證還有很多工作。 您需要創建多個零件/類並使它們一起工作。 它很靈活,您可以創建所需的任何身份驗證系統,但需要一些努力。 使用Guard,它變得更加容易,同時又保持了所有的靈活性。

不是您要查找的組件。

Symfony安全令牌

在閱讀有關Guard Component的文檔中的“令牌”一詞時,所指的是TokenInterface的實現。 Symfony使用這些實現來跟蹤身份驗證狀態。 這些實現永遠不會離開您的應用程序,這是內部的事情。

不是您要查找的令牌。

JSON Web令牌

您正在談論的“令牌”是客戶端可以用來進行身份驗證的信息的某種形式。 這可以是隨機字符串,例如OAuth 2.0協議的“訪問令牌”,也可以是一組獨立且經過簽名的信息,例如JSON Web令牌 (JWT)。

恕我直言,JWT將是目前最具前瞻性的代幣。 熟悉JWT可以很好地閱讀JSON Web令牌剖析

有幾個捆綁包可以輕松地將JWT集成到您的Symfony項目中。 LexikJWTAuthenticationBundle是目前最流行的一種。 我建議你看看:)

暫無
暫無

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

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