Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [Symfony][Symfony2][SF2] Złe przekierowanie po zalogowaniu, Problem z konfiguracją security.yaml
damianooo
post 15.06.2021, 20:02:50
Post #1





Grupa: Zarejestrowani
Postów: 493
Pomógł: 2
Dołączył: 15.07.2011
Skąd: Katowice

Ostrzeżenie: (0%)
-----


Nie wiem czemu po zalogowaniu nie zostaję przekierowany do strony, do której wydaje się powinienem zostać przekierowany a więc do "/tabela" tylko przekierowuje mnie do strony "/" .
Używam Symfony 4.4 .

PS. Chciałem zdebuggować w phpstorm ale mam problem ze skonfigurowaniem poprawnie IDE. Mogę mi ktoś na priv podpowiedzieć ?
Będę bardzo wdzięczny za pomoc.


Mój kod poniżej:

security.yaml:

  1. security:
  2. encoders:
  3. App\Entity\User:
  4. algorithm: bcrypt
  5.  
  6. role_hierarchy:
  7. ROLE_ADMIN: ROLE_USER
  8. ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  9.  
  10. # <a href="https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers" target="_blank">https://symfony.com/doc/current/security.ht...-user-providers</a>
  11. providers:
  12. # used to reload user from session & other features (e.g. switch_user)
  13. app_user_provider:
  14. entity:
  15. class: App\Entity\User
  16. property: username
  17. firewalls:
  18. dev:
  19. pattern: ^/(_(profiler|wdt)|css|images|js)/
  20. security: false
  21.  
  22. main:
  23. anonymous: ~
  24. guard:
  25. authenticators:
  26. - App\Security\LoginFormAuthenticator
  27. logout:
  28. path: app_logout
  29.  
  30. access_control:
  31. - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
  32. - { path: ^/, roles: ROLE_USER}
  33. - { path: ^/admin-panel, roles: ROLE_SUPER_ADMIN }




LoginFormAuthenticator.php


  1. <?php
  2.  
  3. namespace App\Security;
  4.  
  5. use App\Entity\User;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  12. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationExcepti
    on;
  13. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  14. use Symfony\Component\Security\Core\Security;
  15. use Symfony\Component\Security\Core\User\UserInterface;
  16. use Symfony\Component\Security\Core\User\UserProviderInterface;
  17. use Symfony\Component\Security\Csrf\CsrfToken;
  18. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  19. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  20. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  21. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  22.  
  23. class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  24. {
  25. use TargetPathTrait;
  26.  
  27. private $entityManager;
  28. private $urlGenerator;
  29. private $csrfTokenManager;
  30. private $passwordEncoder;
  31.  
  32. public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
  33. {
  34. $this->entityManager = $entityManager;
  35. $this->urlGenerator = $urlGenerator;
  36. $this->csrfTokenManager = $csrfTokenManager;
  37. $this->passwordEncoder = $passwordEncoder;
  38. }
  39.  
  40. public function supports(Request $request)
  41. {
  42. return 'app_login' === $request->attributes->get('_route')
  43. && $request->isMethod('POST');
  44. }
  45.  
  46. public function getCredentials(Request $request)
  47. {
  48. $credentials = [
  49. 'username' => $request->request->get('username'),
  50. 'password' => $request->request->get('password'),
  51. 'csrf_token' => $request->request->get('_csrf_token'),
  52. ];
  53. $request->getSession()->set(
  54. Security::LAST_USERNAME,
  55. $credentials['username']
  56. );
  57.  
  58. return $credentials;
  59. }
  60.  
  61. public function getUser($credentials, UserProviderInterface $userProvider)
  62. {
  63. $token = new CsrfToken('authenticate', $credentials['csrf_token']);
  64. if (!$this->csrfTokenManager->isTokenValid($token)) {
  65. throw new InvalidCsrfTokenException();
  66. }
  67.  
  68. $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);
  69.  
  70. if (!$user) {
  71. // fail authentication with a custom error
  72. throw new CustomUserMessageAuthenticationException('Username could not be found.');
  73. }
  74.  
  75. return $user;
  76. }
  77.  
  78. public function checkCredentials($credentials, UserInterface $user)
  79. {
  80. return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
  81. }
  82.  
  83. /**
  84.   * Used to upgrade (rehash) the user's password automatically over time.
  85.   */
  86. public function getPassword($credentials): ?string
  87. {
  88. return $credentials['password'];
  89. }
  90.  
  91. public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
  92. {
  93. if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
  94. return new RedirectResponse($targetPath);
  95. }
  96.  
  97. return new RedirectResponse($this->urlGenerator->generate('liga_typerow_table'));
  98. }
  99.  
  100. protected function getLoginUrl()
  101. {
  102. return $this->urlGenerator->generate('app_login');
  103. }
  104. }
  105.  
  106.  



MainController .php

  1. /**
  2.   * @Route(
  3.   * "/tabela",
  4.   * name = "liga_typerow_table"
  5.   * )
  6.   * @Template()
  7.   * @param AppExtension $appExtension
  8.   * @return array
  9.   */
  10. public function tableAction(LoggerInterface $logger, TypeService $typeService){
  11.  
  12. $logger->info('this is the table action');
  13. $points = $typeService->getPointsPerMatchday();
  14. return array('points' => $points);
  15. }



Go to the top of the page
+Quote Post
LowiczakPL
post 16.06.2021, 09:20:32
Post #2





Grupa: Zarejestrowani
Postów: 531
Pomógł: 55
Dołączył: 3.01.2016
Skąd: Łowicz

Ostrzeżenie: (0%)
-----


dodaj w security.yaml form login i default_target_path lub jedną z nich dla form_login

  1.  
  2. firewalls:
  3. dev:
  4. pattern: ^/(_(profiler|wdt)|css|images|js)/
  5. security: false
  6.  
  7. main:
  8. anonymous: ~
  9. guard:
  10. authenticators:
  11. - App\Security\LoginFormAuthenticator
  12. logout:
  13. path: app_logout
  14.  
  15. form_login:
  16. always_use_default_target_path: true
  17. default_target_path: /tabela


Ten post edytował LowiczakPL 16.06.2021, 09:20:48


--------------------
Szukam zleceń Symfony, Laravel, Back-End, Front-End, PHP, MySQL ...
Go to the top of the page
+Quote Post
damianooo
post 16.06.2021, 18:53:27
Post #3





Grupa: Zarejestrowani
Postów: 493
Pomógł: 2
Dołączył: 15.07.2011
Skąd: Katowice

Ostrzeżenie: (0%)
-----


Próbowałem już tak wcześniej i nie działa. Dalej przekierowuje mnie do strony "/" .

  1. security:
  2. encoders:
  3. App\Entity\User:
  4. algorithm: bcrypt
  5.  
  6. role_hierarchy:
  7. ROLE_ADMIN: ROLE_USER
  8. ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  9.  
  10. # <a href="https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers" target="_blank">https://symfony.com/doc/current/security.ht...-user-providers</a>
  11. providers:
  12. # used to reload user from session & other features (e.g. switch_user)
  13. app_user_provider:
  14. entity:
  15. class: App\Entity\User
  16. property: username
  17. firewalls:
  18. dev:
  19. pattern: ^/(_(profiler|wdt)|css|images|js)/
  20. security: false
  21.  
  22. main:
  23. anonymous: ~
  24. guard:
  25. authenticators:
  26. - App\Security\LoginFormAuthenticator
  27. logout:
  28. path: app_logout
  29.  
  30. form_login:
  31. always_use_default_target_path: true
  32. default_target_path: /tabela
  33.  
  34. access_control:
  35. - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
  36. - { path: ^/, roles: ROLE_USER}
  37. - { path: ^/admin-panel, roles: ROLE_SUPER_ADMIN }


Ten post edytował damianooo 16.06.2021, 18:54:50
Go to the top of the page
+Quote Post
LowiczakPL
post 16.06.2021, 19:01:40
Post #4





Grupa: Zarejestrowani
Postów: 531
Pomógł: 55
Dołączył: 3.01.2016
Skąd: Łowicz

Ostrzeżenie: (0%)
-----


z access_control wyrzuć tą linię


  1. - { path: ^/, roles: ROLE_USER}



a następnie jak zadziała usuń to co zaproponowałem wcześniej

Chodzi o to że wymagasz pełnego zalogowania dla / czyli w sesji masz zapamiętaną ścieżkę / na którą Symfony przekierowuje Cie po zalogowaniu ponieważ najpierw jest sprawdzana sesja gdzie chcesz się dostać a następnie zdefiniowane ścieżka
  1.  
  2. if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
  3. return new RedirectResponse($targetPath);
  4. }
  5.  
  6. return new RedirectResponse($this->urlGenerator->generate('liga_typerow_table'));



Ten post edytował LowiczakPL 16.06.2021, 19:10:44


--------------------
Szukam zleceń Symfony, Laravel, Back-End, Front-End, PHP, MySQL ...
Go to the top of the page
+Quote Post
damianooo
post 16.06.2021, 19:14:36
Post #5





Grupa: Zarejestrowani
Postów: 493
Pomógł: 2
Dołączył: 15.07.2011
Skąd: Katowice

Ostrzeżenie: (0%)
-----


ok faktycznie działa. Dzięki.

Ale jeszcze mam problem z wylogowaniem bo przekierowuje mnie do "/" zamiast do "/login"
Go to the top of the page
+Quote Post
LowiczakPL
post 17.06.2021, 07:58:52
Post #6





Grupa: Zarejestrowani
Postów: 531
Pomógł: 55
Dołączył: 3.01.2016
Skąd: Łowicz

Ostrzeżenie: (0%)
-----


Wydaje mi się ze /login to takie sobie miejsce na wylądowanie po wylogowaniu

... w security masz parametr logout:

  1. logout:
  2. path: /login


--------------------
Szukam zleceń Symfony, Laravel, Back-End, Front-End, PHP, MySQL ...
Go to the top of the page
+Quote Post
damianooo
post 21.06.2021, 21:32:44
Post #7





Grupa: Zarejestrowani
Postów: 493
Pomógł: 2
Dołączył: 15.07.2011
Skąd: Katowice

Ostrzeżenie: (0%)
-----


Dzięki za pomoc.

Z tym wylogowaniem trochę inaczej ma być:

logout:
path: /logout
target: /login

poza tym musiałem odkomentować:

- { path: ^/, roles: ROLE_USER}

bo się działy dziwne rzeczy po wylogowaniu bo niby byłem wylogowany ale widziałem wszystkie strony tak jakbym był zalogowany.

Masz i tak jeszcze jednego plusa ode mnie.
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 28.04.2024 - 04:25