3

我在为我的新 Symfony2 应用程序验证用户时遇到问题。

该应用程序通过 API 获取所有信息,因此不使用数据库。当用户进入登录页面时,他会在登录表单中介绍用户名和密码。然后,我必须使用 API 调用对他进行身份验证。如果不是用户,则此 API 调用返回“false”,如果是正确的用户,则返回令牌密钥和令牌密钥。使用这个令牌密钥和秘密,在用户会话期间,我可以发出渲染应用程序所有页面所需的所有 API 请求。一旦用户会话结束并且令牌密钥和秘密被删除,用户必须再次登录。

我真的不知道如何实现它。我读了这个http://symfony.com/doc/current/cookbook/security/custom_provider.html和那个http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html,我仍然如此丢失的... :(

谁能帮我?

太感谢了 :)

4

1 回答 1

4

If you want to write custom authentication you have found the correct links. As an example you can see the implementation of the OAuth authorization HWIOAuthBundle. But keep in mind that this type of authentication creates a user on your system. If you do not use a database, you must make a request to the API every time user send a request.

First you need to understand that there is no magic. On every request symfony checks if url matches one of the specified firewalls (see secutity.yml). Listener that fired you can see in the firewall factory. If matches are found, the action switches to the corresponding AuthenticationListener. Listener attempts to authenticate the credewntials by creating Token, which is sended to AuthenticationProvider

$this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));

in AuthenticationProvider

public function authenticate(TokenInterface $token) {
    ...
}

AuthenticationProvider try to get user via UserProvider. In case of success, Token stored in the session. On subsequent requests, ContextListener comes into play first, checks the session, extract token and send it to AuthenticationProvider similar.

In general terms, the scheme looks like that. More info you can find examining the source code of Symfony Security component.

Really good starting point is a UsernamePasswordFormAuthenticationListener. It just take login and password from request and make simplest UsernamePasswordToken.

protected function attemptAuthentication(Request $request)
{
    ...
}

Good luck!

于 2013-04-27T14:38:26.440 回答