Symfony身份验证api密钥丢失会话

时间:2014-03-05 22:49:25

标签: php api symfony authentication

我按照本指南http://symfony.com/doc/current/cookbook/security/api_key_authentication.html通过API KEY进行身份验证。

在调用最后一个方法身份验证令牌后,我可以登录用户,但不会保留会话。

return new PreAuthenticatedToken(
        $user,
        $apiKey,
        $providerKey,
        $user->getRoles()
    );

我还尝试使用以下方法进行身份验证:

$user = new User("Test", null, array("ROLE_USER"));
$token = new UsernamePasswordToken($user, null, 'secured_area', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_secured_area',serialize($token));

这两种情况我只能将用户登录到单个页面,而不是所有项目。

安全就像指南:

firewalls:
    secured_area:
        pattern: ^/testproject
        stateless: true
        simple_preauth:
            authenticator: apikey_authenticator

由于

[更新]

$user = new ApiKeyUserProvider();
$user = $user->loadUserByUsername("111111");

$apiKeyProvider = $this->get('apikey_authenticator');
$token = $apiKeyProvider->authenticateToken("111111",$user);
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_secured_area',serialize($token));

loadUserByUsername就像symfony guide。

由于

2 个答案:

答案 0 :(得分:1)

如果您正确遵循本指南,则应自动进行身份验证。您需要做的就是将参数apikey附加到请求的末尾。

IE:

www.mydomain.com/testproject/get-some-random-data?apikey=vdsadbrfadbfda

Symfony将在您的防火墙中接收此请求并通过ApiKeyAuthenticator运行它。

如果您希望将该身份验证保存在会话中,以便后续请求不需要apikey,那么您可以在stateless

中将security.yml配置更改为false

所以改变:

firewalls:
    secured_area:
        pattern: ^/testproject
        stateless: true
        simple_preauth:
            authenticator: apikey_authenticator

要:

firewalls:
    secured_area:
        pattern: ^/testproject
        stateless: false
        simple_preauth:
            authenticator: apikey_authenticator

查看:http://symfony.com/doc/current/cookbook/security/api_key_authentication.html#cookbook-security-api-key-session

您是否在UserProvider中实现了refreshUser方法?

public function refreshUser(UserInterface $user)
{
    // this is used for storing authentication in the session
    // but in this example, the token is sent in each request,
    // so authentication can be stateless. Throwing this exception
    // is proper to make things stateless
    throw new UnsupportedUserException();
}

需要成为:

public function refreshUser(UserInterface $user)
{
    // $user is the User that you set in the token inside authenticateToken()
    // after it has been deserialized from the session

    // you might use $user to query the database for a fresh user
    // $id = $user->getId();
    // use $id to make a query

    // if you are *not* reading from a database and are just creating
    // a User object (like in this example), you can just return it
    return $user;
}

答案 1 :(得分:0)

我遇到了同样的问题,发现apiKey被保存为令牌凭据。如果您未设置以下内容,则会删除这些内容:

security:
    erase_credentials:    false