Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [SF][Symfony2][SF2]Autentykacja użytkownika i security.yml
Forum PHP.pl > Forum > PHP > Frameworki
webmaniak
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
M4ver7071
Zamień na to :
  1. _check_path:
  2. pattern: /login-check
webmaniak
Robiłem tak też, niestety problem jest ten sam ;/
M4ver7071
Ogólnie to w Twoim routingu nie widzę trasy dla logowania.
webmaniak
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ę.
prz3kus
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
webmaniak
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?
Turson
  1. return array();
załatwi sprawę

Albo jak masz w yml routing, to dodaj to trasy definicję 'defaults' z nazwą kontrolera
M4ver7071
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źć ?
M4ver7071
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źć ?
webmaniak
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 }
M4ver7071
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. }
webmaniak
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 ;/
prz3kus
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. }
webmaniak
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 ;/
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.