我設定了基本系統以將非登錄用戶重定向到登錄頁面
// security.yaml
main:
lazy: true
provider: app_user_provider
form_login:
# "login" is the name of the route created previously
login_path: login
check_path: login
[...]
access_control:
- { path: ^/home, roles: ROLE_USER }
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
一切正常!當我沒有登錄時,它會將我正確重定向到我的登錄頁面。另一方面,當我連接時,我希望用戶被重定向到家而不是出現錯誤(我目前有)。

我知道錯誤是正常的,但我想要一個重定向,我覺得它更干凈,帶有錯誤訊息的重定向會更好。
這是我的控制器:
class LoginController extends AbstractController
{
#[Route('/login', name: 'login')]
public function index(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('login/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
}
我的控制器類似于 symfony 檔案: https ://symfony.com/doc/current/security.html#form-login
uj5u.com熱心網友回復:
在您的登錄方法中添加重定向,以便如果用戶登錄,他將被重定向到您想要的任何頁面。
您可以在您的方法中自動裝配use Symfony\Component\Security\Core\User\UserInterface;以檢索登錄用戶(如果是這種情況),而無需使用TokenStorage.
/**
* @Route("/login", name="login")
*/
public function login(AuthenticationUtils $authenticationUtils, UserInterface $user = null): Response
{
if($user !== null){
$this->redirectToRoute('home');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
uj5u.com熱心網友回復:
我在這里想到了這個解決方案,但根據我在下面提出的幾篇文章和意見,我正在尋找一個更正統的解決方案和標準:
“想到的第一個想法。嗯,這是一種幼稚的方法,但它有效。復制粘貼三個控制器,瞧,測驗剛剛通過。它只有三頁,所以沒關系,不是嗎?
class SomeController extends BaseController
{
public function someAction()
{
if ($this->isUserLogged()) {
return $this->redirectToRoute('somewhere');
}
// do default action
}
}
多個控制器中的重復可能會成為大問題。如果每個動作都需要做這樣的檢查,想象一下代碼。例如,如果您想強制用戶每月更改密碼?最重要的是,如果您使用 FOSUserBundle(或任何其他外部用戶捆綁包),您必須覆寫第三個捆綁包的控制器。這是很多樣板代碼,所以我寧愿避免這種解決方案。不要重復我的錯誤并更仔細地閱讀 StackOverflow :) "
所以這是這篇文章,事實上,如果我想將管理頁面限制為我的角色:
# - { path: ^/admin, roles: ROLE_ADMIN }
“我不會手動測驗用戶是否在所有頁面上都是管理員?我正在尋找標準解決方案......但感謝您的建議
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/422403.html
標籤:
上一篇:Shopware6授權客戶
