如果登錄用戶轉到登錄操作,我想將它們重定向到另一個頁面。但我不知道如何在loginAction
方法中檢測用戶是否已登錄。當我不在時,登錄操作中的安全上下文使我看起來已經退出。在symfony2中,當我登錄時,登錄動作顯示我已退出登錄
作爲測試,我在登錄該網站時請求以下兩頁。爲什麼我無法在登錄操作中訪問用戶?
這裏是我的登錄操作:
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的回答後T,我想他們可能是
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 }
但是當我訪問/登錄時,我有一個重定向循環錯誤。
回覆您的回答,我編輯了原帖。你能看看嗎? – mattalxndr
將'access_control:'放在'security:'下,而不是'providers:' – ilanco