如果登录用户进入登录操作,我想将他们重定向到另一个页面。但我不知道如何在方法内部检测用户是否登录loginAction
。登录操作中的安全上下文使我在没有登录时似乎已注销。
作为测试,我在登录网站时请求以下两个页面。为什么我无法在登录操作中访问用户?
这是我的登录操作:
public function loginAction()
{
$token = $this->get('security.context')->getToken();
print_r(get_class($token));
// Outputs "Symfony\Component\Security\Core\Authentication\Token\AnonymousToken"
print_r($token->getUser());
// Outputs "anon."
}
这是应用程序中的一个通用操作,受登录名保护:
public function regularAction()
{
$token = $this->get('security.context')->getToken();
print_r(get_class($token));
// Outputs "Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken"
print_r(get_class($token->getUser()));
// Outputs "Company\BaseBundle\Entity\User"
}
这是我的security.yml
:
security:
encoders:
Company\BaseBundle\Entity\User:
algorithm: sha1
iterations: 1
encode_as_base64: false
providers:
main:
entity: { class: Company\BaseBundle\Entity\User, property: user_name }
firewalls:
login_firewall:
pattern: ^/login$
anonymous: ~
main:
pattern: ^/
form_login:
login_path: /login
check_path: /login_check
post_only: true
always_use_default_target_path: false
default_target_path: /
use_referer: true
failure_path: null
failure_forward: false
username_parameter: user_name
password_parameter: password_hash
csrf_parameter: _csrf_token
intention: authenticate
logout:
path: /logout
target: /
acl:
connection: default
编辑:我不认为我的其余防火墙是相关的,但在阅读了 ilanco 的回答后,我认为它们可能是
security:
encoders:
Company\BaseBundle\Entity\User:
algorithm: sha1
iterations: 1
encode_as_base64: false
providers:
main:
entity: { class: Company\BaseBundle\Entity\User, property: user_name }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login_firewall:
pattern: ^/login$
anonymous: ~
password_reset:
pattern: ^/passwordreset/*$
anonymous: ~
error_firewall:
pattern: ^/error/.*$
anonymous: ~
unsupported_broswers:
pattern: ^/unsupported$
anonymous: ~
security_question_firewall:
pattern: ^/user/(locked|security_question)/(new)*$
anonymous: ~
api_firewall:
pattern: ^/api/.*$
provider: main
http_basic:
realm: "Secured API Area. Login with your regular credentials"
provider: main
main:
pattern: ^/
form_login:
login_path: /login
check_path: /login_check
post_only: true
always_use_default_target_path: false
default_target_path: /
use_referer: true
failure_path: null
failure_forward: false
username_parameter: user_name
password_parameter: password_hash
csrf_parameter: _csrf_token
intention: authenticate
logout:
path: /logout
target: /
acl:
connection: default
按照 ilanco 的建议,我删除了这个:
login_firewall:
pattern: ^/login$
anonymous: ~
并将其直接添加到该providers
部分下:
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
但是当我访问 /login 时出现重定向循环错误。