0
votes

I want to do a redirect in the loginAction if the user is authenticated.

My security.yml.

    firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

    login:
        pattern:  ^/(en|de)/login
        security: false

    secured_area:
        pattern:    ^/
        anonymous:  ~
        http_basic:
            realm: "Secured Area"
        form_login:
            check_path: frontend_account_security_check
            login_path: frontend_account_login
            #use_referer:        true
            #always_use_default_target_path: true
            default_target_path: frontend_main_index
            #default_target_path: frontend_account_my_account
            #target_path_parameter: frontend_account_my_account
        logout: 
            path:   /de/secured/logout
            target: /de/
            #default_target_path: frontend_account_login
            #anonymous: ~
        http_basic:
            realm: "Secured Demo Area"



access_control:
    #- { path: ^/secured/en/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/(en|de)/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }

My action:

    $auth = $this->get('security.context')->getToken()->getUser();
        if ($auth == 'anon.') {
            $auth = FALSE;
        } else {
           return $this->redirect($this->generateUrl('frontend_main_index'));
        }

My error: Call to a member function getUser() on a non-object

I also tried: $this->get('security.context')->isGranted('ROLE_USER') with the error:

The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

I can I do a redirect if a user is logged in.

1
$this->get('security.context')->isGranted('ROLE_USER') should work. What kind of error do you get with this line and how does your complete loginAction look like?Syjin
Thanks for the hint. But I do get an error too. I updated my question.craphunter

1 Answers

2
votes

The problem seems to be this part:

login:
    pattern:  ^/(en|de)/login
    security: false

Remove this from your security.yml and you should be able to check the user role with

$this->get('security.context')->isGranted('ROLE_USER')

and redirect accordingly. I think this has something to do with firewalls not sharing their security context. A detailed explanation can be found in the documentation about Symfony Security


Also note that you should either remove

    http_basic:
        realm: "Secured Area"

or

    http_basic:
        realm: "Secured Demo Area"