Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [SF][Symfony2][SF2]Autentykacja użytkownika i security.yml
webmaniak
post 1.03.2015, 14:56:31
Post #1





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Witam,
Mam problem z plikiem security.yml i routingiem -tak sądzę. Poniżej plik security.yml
Kod
# you can read more about security in the related section of the documentation
# http://symfony.com/doc/current/book/security.html
security:
    # http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
    encoders:
        Common\UserBundle\Entity\User:
            algorithm: bcrypt

    # http://symfony.com/doc/current/book/security.html#hierarchical-roles
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        blog_users:
            entity:
                class: CommonUserBundle:User
                property: username

    # the main part of the security, where you can set up firewalls
    # for specific sections of your app
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern:  ^/(_(profiler|wdt)|css|img|js)/
            security: false

        # secures part of the application
        blog_security:
            pattern:    ^/
            anonymous: ~
            form_login:
                check_path: _check_path
                login_path: _blog_login
                default_target_path: blog_index
            logout:
                path:   _logout
                target: blog_index
            #http_basic:
            #    realm: "Secured Demo Area"

    # with these settings you can restrict or allow access for different parts
    # of your application based on roles, ip, host or methods
    # http://symfony.com/doc/current/book/security.html#security-book-access-control-matching-options
    access_control:
        #- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }

routing.yml w CommonUserBundle:
Kod
common_user:
    resource: "@CommonUserBundle/Controller/"
    type:     annotation
    prefix:   /

_check_path:
    path: /login-check

_logout:
    path: /logout

Problem polega na tym że po kliku na "Zaloguj" następuje przekierowanie na ścieżkę lgon-check, co z kolei skutkuje wyświetleniem błędu:
  1. Unable to find the controller for path "/login-check". Maybe you forgot to add the matching route in your routing configuration?

Podpowiedzi które znalazłem do tej pory nie naprowadziły mnie niestety na rozwiązanie problemu. Od razu dodam że zapoznałem się ze stroną dokumentacji:
http://symfony.com/doc/current/book/securi...-authentication
Tyle tylko że nie potrafię przenieść opisu, który tam jest na mój kod ;/ jakieś sugestie co tutaj jest źle? Będę wdzięczny za pomoc i z góry dziękuję smile.gif


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
M4ver7071
post 1.03.2015, 18:16:45
Post #2





Grupa: Zarejestrowani
Postów: 63
Pomógł: 0
Dołączył: 26.06.2014

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


Zamień na to :
  1. _check_path:
  2. pattern: /login-check
Go to the top of the page
+Quote Post
webmaniak
post 2.03.2015, 07:09:01
Post #3





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Robiłem tak też, niestety problem jest ten sam ;/


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
M4ver7071
post 2.03.2015, 10:07:09
Post #4





Grupa: Zarejestrowani
Postów: 63
Pomógł: 0
Dołączył: 26.06.2014

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


Ogólnie to w Twoim routingu nie widzę trasy dla logowania.
Go to the top of the page
+Quote Post
webmaniak
post 2.03.2015, 11:04:30
Post #5





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Chodzi Ci o _blog_login a właściwie blog_login(w security.yml mam podkreślenie niepotrzebne - ale to też sprawdzałem i nie jest przyczyną)? Jeśli tak to:
  1. namespace Common\UserBundle\Controller;
  2.  
  3. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Security\Core\SecurityContextInterface;
  8.  
  9. class LoginController extends Controller
  10. {
  11. /**
  12.   * @Route(
  13.   * "/login",
  14.   * name="blog_login"
  15.   * )
  16.   *
  17.   * @Template()
  18.   */
  19. public function loginAction(Request $request)
  20. {
  21. $session = $this->get('session');
  22.  
  23. if($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
  24. $loginError = $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
  25. } else {
  26. $loginError = $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
  27. }
  28.  
  29. $userName = $session->get(SecurityContextInterface::LAST_USERNAME);
  30.  
  31. return array(
  32. 'loginError' => $loginError,
  33. 'userName' => $userName
  34. );
  35. }
  36. }

A jeśli chodzi o coś innego to sprecyzuj proszę.


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
prz3kus
post 2.03.2015, 15:20:51
Post #6





Grupa: Zarejestrowani
Postów: 260
Pomógł: 30
Dołączył: 22.01.2007

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


Masz dodane w Controller

  1. /**
  2.   * @Route("/login_check", name="_check_path")
  3.   */
  4. public function securityCheckAction()
  5. {
  6. // The security layer will intercept this request
  7. }



questionmark.gif
Go to the top of the page
+Quote Post
webmaniak
post 2.03.2015, 17:16:44
Post #7





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Nie, nie mam. Ale za to odpowiada chyba:
Kod
_check_path:
    path: /login-check

?
W każdym razie spróbowałem dodać tą akcję - no ale teraz muszę tam coś zwrócić:
  1. The controller must return a response

Zatem czy to jest jedyny sposób na rozwiązanie tego problemu?


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
Turson
post 2.03.2015, 19:19:03
Post #8





Grupa: Zarejestrowani
Postów: 4 291
Pomógł: 829
Dołączył: 14.02.2009
Skąd: łódź

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


  1. return array();
załatwi sprawę

Albo jak masz w yml routing, to dodaj to trasy definicję 'defaults' z nazwą kontrolera
Go to the top of the page
+Quote Post
M4ver7071
post 2.03.2015, 19:29:55
Post #9





Grupa: Zarejestrowani
Postów: 63
Pomógł: 0
Dołączył: 26.06.2014

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


Zapytam tutaj aby nie robić drugiego tematu. Mam pytanie, mam CRUD do produktów ale chce ograniczyć dostęp do niektórych metod, ale nie chce tego robić za każdym razem z palca, ponieważ jak dodam nową funkcjonalność to muszę pamiętać o dodaniu do security.yml. Myślałem nad zrobieniem dodatkowego serwisu który byłby wywoływany w ProductController a następnie udostępniał dostęp według wytycznych. Czyli dla metody index, show daj dostęp dla wszystkich reszta tylko dla admina(taki przykład). Czy macie jakieś sugestie jak to ugryźć ?
Go to the top of the page
+Quote Post
M4ver7071
post 2.03.2015, 19:29:56
Post #10





Grupa: Zarejestrowani
Postów: 63
Pomógł: 0
Dołączył: 26.06.2014

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


Zapytam tutaj aby nie robić drugiego tematu. Mam pytanie, mam CRUD do produktów ale chce ograniczyć dostęp do niektórych metod, ale nie chce tego robić za każdym razem z palca, ponieważ jak dodam nową funkcjonalność to muszę pamiętać o dodaniu do security.yml. Myślałem nad zrobieniem dodatkowego serwisu który byłby wywoływany w ProductController a następnie udostępniał dostęp według wytycznych. Czyli dla metody index, show daj dostęp dla wszystkich reszta tylko dla admina(taki przykład). Czy macie jakieś sugestie jak to ugryźć ?
Go to the top of the page
+Quote Post
webmaniak
post 2.03.2015, 20:28:48
Post #11





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Cytat(Turson @ 2.03.2015, 19:19:03 ) *
  1. return array();
załatwi sprawę

Albo jak masz w yml routing, to dodaj to trasy definicję 'defaults' z nazwą kontrolera

No właśnie nie wystarczy:
  1. The controller must return a response (Array() given).
  2. 500 Internal Server Error - LogicException

I nie ma znaczenia czy mam to w adnotacjach czy w routing.yml:
Kod
_check_path:
    path: /login_check
    defaults:  { _controller: CommonUserBundle:Login:securityCheck }


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
M4ver7071
post 2.03.2015, 20:44:27
Post #12





Grupa: Zarejestrowani
Postów: 63
Pomógł: 0
Dołączył: 26.06.2014

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


Daj :

  1. public function loginAction(Request $request)
  2. {
  3. $session = $request->getSession();
  4.  
  5. // get the login error if there is one
  6. if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
  7. $error = $request->attributes->get(
  8. SecurityContext::AUTHENTICATION_ERROR
  9. );
  10. } else {
  11. $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
  12. $session->remove(SecurityContext::AUTHENTICATION_ERROR);
  13. }
  14.  
  15. return $this->render(
  16. 'AcneUserBundle:Security:login.html.twig',
  17. // last username entered by the user
  18. 'last_username' => $session->get(SecurityContext::LAST_USERNAME),
  19. 'error' => $error,
  20. )
  21. );
  22. }
Go to the top of the page
+Quote Post
webmaniak
post 2.03.2015, 21:02:12
Post #13





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Dałem tak:
  1. public function loginAction(Request $request)
  2. {
  3. $session = $request->getSession();
  4.  
  5. // get the login error if there is one
  6. if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
  7. $error = $request->attributes->get(
  8. SecurityContext::AUTHENTICATION_ERROR
  9. );
  10. } else {
  11. $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
  12. $session->remove(SecurityContext::AUTHENTICATION_ERROR);
  13. }
  14.  
  15. $username = $session->get(SecurityContext::LAST_USERNAME);
  16.  
  17. return $this->render(
  18. 'CommonUserBundle:Login:login.html.twig',
  19. // last username entered by the user
  20. 'userName' => $username,
  21. 'last_username' => $session->get(SecurityContext::LAST_USERNAME),
  22. 'error' => $error,
  23. )
  24. );
  25. }

Czyli tylko zmieniłem nazwę renderowanego pliku widoku(routing przeniosłem do routing.yml). Problem nadal jest taki sam: The controller must return a response (Array() given). dla /login_check ;/


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
Go to the top of the page
+Quote Post
prz3kus
post 3.03.2015, 20:26:32
Post #14





Grupa: Zarejestrowani
Postów: 260
Pomógł: 30
Dołączył: 22.01.2007

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


webmaniak
Nic w tej metodzie nie trzeba zwracać, zainstaluj sobie czyste symfony i popatrz na przykład z bundla który jest domyślnie wbudowany, tam masz gotowca


_________________

Cytat(M4ver7071 @ 2.03.2015, 19:29:55 ) *
Zapytam tutaj aby nie robić drugiego tematu. Mam pytanie, mam CRUD do produktów ale chce ograniczyć dostęp do niektórych metod, ale nie chce tego robić za każdym razem z palca, ponieważ jak dodam nową funkcjonalność to muszę pamiętać o dodaniu do security.yml. Myślałem nad zrobieniem dodatkowego serwisu który byłby wywoływany w ProductController a następnie udostępniał dostęp według wytycznych. Czyli dla metody index, show daj dostęp dla wszystkich reszta tylko dla admina(taki przykład). Czy macie jakieś sugestie jak to ugryźć ?


Nie wystarczy ograniczanie do metod w stylu:

  1. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  2.  
  3. /**
  4.  * @Security("has_role('ROLE_ADMIN')")
  5.  */
  6. public function helloAction($name)
  7. {
  8. // ...
  9. }


Ten post edytował prz3kus 3.03.2015, 20:27:53
Go to the top of the page
+Quote Post
webmaniak
post 4.04.2015, 14:45:08
Post #15





Grupa: Zarejestrowani
Postów: 371
Pomógł: 30
Dołączył: 14.04.2010

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


Cytat(prz3kus @ 3.03.2015, 20:26:32 ) *
webmaniak
Nic w tej metodzie nie trzeba zwracać, zainstaluj sobie czyste symfony i popatrz na przykład z bundla który jest domyślnie wbudowany, tam masz gotowca

Dzięki, dopiero teraz mam czas by znowu spróbować rozwiązać problem. Musiałem ja coś pomieszać w plikach i dlatego nie działa to tak jak powinno. Z pewnością podzielę się informacjami co było nie tak jak rozwiążę problem smile.gif

Witam,
próbowałem, kombinowałem by na moim kodzie odpalić to logowanie - problem jest w sytuacji gdy używam entity user. Postanowiłem od podszewki poznać sposób autentykacji w symfony2. Zaczołem od:
http://symfony.com/doc/current/book/security.html
A po sekcji A) jest link do:
http://symfony.com/doc/current/cookbook/se...ogin_setup.html
Zacząłem robić wszystko zgodnie z tym opisem. Jednak po utworzeniu SecurityController i metod login i loginCheck, jak poniżej:
  1. <?php
  2.  
  3. namespace AppBundle\Controller;
  4.  
  5.  
  6. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  7. use Symfony\Component\HttpFoundation\Request;
  8.  
  9. class SecurityController extends Controller
  10. {
  11.  
  12. /**
  13.   * @Route("/login", name="login_route")
  14.   */
  15. public function loginAction(Request $request)
  16. {
  17. $authenticationUtils = $this->get('security.authentication_utils');
  18.  
  19. // get the login error if there is one
  20. $error = $authenticationUtils->getLastAuthenticationError();
  21.  
  22. // last username entered by the user
  23. $lastUsername = $authenticationUtils->getLastUsername();
  24.  
  25. return $this->render(
  26. 'security/login.html.twig',
  27. // last username entered by the user
  28. 'last_username' => $lastUsername,
  29. 'error' => $error,
  30. )
  31. );
  32. }
  33.  
  34. /**
  35.   * @Route("/login_check", name="login_check")
  36.   */
  37. public function loginCheckAction()
  38. {
  39. // this controller will not be executed,
  40. // as the route is handled by the Security system
  41. }
  42. }

mam błąd w postaci:
Kod
FileLoaderImportCircularReferenceException in FileLoader.php line 97: Circular reference detected in "C:\xampp\htdocs\sf2\app/config/routing_dev.yml" ("C:\xampp\htdocs\sf2\app/config/routing_dev.yml" > "C:\xampp\htdocs\sf2\app/config\routing.yml" > "C:\xampp\htdocs\sf2\src\AppBundle/Controller/" > "C:\xampp\htdocs\sf2\app/config/routing_dev.yml").

    in FileLoader.php line 97
    at FileLoader->import('C:\xampp\htdocs\sf2\app/config/routing_dev.yml', null, false, 'C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml') in YamlFileLoader.php line 155
    at YamlFileLoader->parseImport(object(RouteCollection), array('resource' => 'C:\xampp\htdocs\sf2\app/config/routing_dev.yml'), 'C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml', 'C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml') in YamlFileLoader.php line 91
    at YamlFileLoader->load('C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml', 'yaml') in DelegatingLoader.php line 45
    at DelegatingLoader->load('C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml', 'yaml') in DelegatingLoader.php line 58
    at DelegatingLoader->load('C:\xampp\htdocs\sf2\app\cache\dev/assetic/routing.yml', 'yaml') in classes.php line 3418
    at Router->getRouteCollection() in classes.php line 3388
    at Router->getGeneratorDumperInstance() in classes.php line 3369
    at Router->getGenerator() in classes.php line 3314
    at Router->generate('_profiler', array('token' => '558d6d')) in WebDebugToolbarListener.php line 66
    at WebDebugToolbarListener->onKernelResponse(object(FilterResponseEvent), 'kernel.response', object(TraceableEventDispatcher))
    at call_user_func(array(object(WebDebugToolbarListener), 'onKernelResponse'), object(FilterResponseEvent), 'kernel.response', object(TraceableEventDispatcher)) in WrappedListener.php line 61
    at WrappedListener->__invoke(object(FilterResponseEvent), 'kernel.response', object(ContainerAwareEventDispatcher))
    at call_user_func(object(WrappedListener), object(FilterResponseEvent), 'kernel.response', object(ContainerAwareEventDispatcher)) in classes.php line 3916
    at EventDispatcher->doDispatch(array(object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener)), 'kernel.response', object(FilterResponseEvent)) in classes.php line 3849
    at EventDispatcher->dispatch('kernel.response', object(FilterResponseEvent)) in classes.php line 4010
    at ContainerAwareEventDispatcher->dispatch('kernel.response', object(FilterResponseEvent)) in TraceableEventDispatcher.php line 112
    at TraceableEventDispatcher->dispatch('kernel.response', object(FilterResponseEvent)) in bootstrap.php.cache line 3046
    at HttpKernel->filterResponse(object(Response), object(Request), '2') in bootstrap.php.cache line 3041
    at HttpKernel->handleRaw(object(Request), '2') in bootstrap.php.cache line 2988
    at HttpKernel->handle(object(Request), '2', true) in bootstrap.php.cache line 3137
    at ContainerAwareHttpKernel->handle(object(Request), '2', true) in ExceptionListener.php line 58
    at ExceptionListener->onKernelException(object(GetResponseForExceptionEvent), 'kernel.exception', object(TraceableEventDispatcher))
    at call_user_func(array(object(ExceptionListener), 'onKernelException'), object(GetResponseForExceptionEvent), 'kernel.exception', object(TraceableEventDispatcher)) in WrappedListener.php line 61
    at WrappedListener->__invoke(object(GetResponseForExceptionEvent), 'kernel.exception', object(ContainerAwareEventDispatcher))
    at call_user_func(object(WrappedListener), object(GetResponseForExceptionEvent), 'kernel.exception', object(ContainerAwareEventDispatcher)) in classes.php line 3916
    at EventDispatcher->doDispatch(array(object(WrappedListener), object(WrappedListener)), 'kernel.exception', object(GetResponseForExceptionEvent)) in classes.php line 3849
    at EventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in classes.php line 4010
    at ContainerAwareEventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in TraceableEventDispatcher.php line 112
    at TraceableEventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in bootstrap.php.cache line 3058
    at HttpKernel->handleException(object(FileLoaderLoadException), object(Request), '1') in bootstrap.php.cache line 2994
    at HttpKernel->handle(object(Request), '1', true) in bootstrap.php.cache line 3137
    at ContainerAwareHttpKernel->handle(object(Request), '1', true) in bootstrap.php.cache line 2381
    at Kernel->handle(object(Request)) in app_dev.php line 28

Czy ktoś wie skąd on wynika i może mnie naprowadzić na rozwiązanie?
Z góry dziękuję smile.gif

Edit:
Problem rozwiązany. Brakowało:
  1. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

Eh ;/

Ten post edytował webmaniak 4.04.2015, 16:16:06


--------------------
Pomogłem - kliknij , wprowadziłem w błąd - poinformuj niżej lub na pm.
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: 24.05.2024 - 00:55