Redirect to the url of the clicked (referred) link

2019-05-31 16:25发布

问题:

I have a scenario where the user receives an email from the system with a specific link which requires login. say for example the link is http://test.url.com/product/2. Where clicking on this link redirects the user to the sign in page and should redirect to the received url upon success login.

But the issue I am having is the system always redirects to the default location which is http://test.url.com/dashboard.

To implement this I used http://symfony.com/doc/current/reference/configuration/security.html#redirecting-after-login use_referer: true in security.yml and to test it I have used print_r($request->headers->get('referer')); on the sign in page.

But this always returns null when I click the link from the email but, it returns the proper referrer url when I logout of the system and lands on the sign in page.

EDIT - security.yml

security:
    providers:
    in_memory:
        memory: ~

    webservice:
        id: user_provider
    encoders:
        Project\Bundle\LoginBundle\Security\User\User: plaintext

    access_control: 
      - { path: ^/signin, role: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: "^/(signup|forgotpassword|resetpassword/[0-9a-z]+)?$", roles: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: ^/, roles: IS_AUTHENTICATED_FULLY }      

    firewalls:
      secured_area:
    pattern:   ^/
    anonymous: ~
    form_login:
      login_path: /signin
      check_path: _security_check
    access_denied_url: forgotpassword
      dev:
    pattern: ^/(_(profiler|wdt)|css|images|js)/
    security: false

      default:
    anonymous: true

回答1:

So you have 2 choices:

You can either populate the referer manually or you can have it populate in your controller by causing a login redirect by specifying it in your security.yml. i recommend the security.yml way as i haven't actually tried the manual population because i don't trust myself or anyone else for that matter to always remember to populate the refer in those situations. security.yml also has the benefit of not having redirect code all over the place.

$request->getSession()->set('referer', $request->attributes->all());

or

access_control:
    - { path: ^/product/.*, roles: IS_AUTHENTICATED_REMEMBERED }