Search code examples
symfonysecurityhttp-authenticationsymfony-2.8

Gracefully handle an aborted HTTP authentication browser login attempt in Symfony 2 application


I would like to gracefully handle an aborted HTTP login attempt in my SF2 application.

Currently, when I click the following anchor I get the standard browser HTTP authentication pop-up. However, if I click 'cancel' I get through to a blank /secret/landing.

How can I modify my security/firewall configuration to simply close the modal and remain on the same page?

<a href="/secret/landing/">Sign In</a>

My security.yml looks like this:

security:
    providers:
        in_memory:
            memory:
                users:
                    crmpiccosecret:
                        password: rfc1872
                        roles: 'ROLE_SECRET'
    firewalls:
        secret:
            pattern: ^/secret/$
            anonymous: true
        secret_secured:
            pattern: ^/secret/.*$
            http_basic: ~
            provider: in_memory
            context: secret
    access_control:
        - { path: ^/secret, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/secret/.*, roles: ROLE_SECRET }

enter image description here


Solution

  • I found the desired behaviour can be achieved by changing the href to data-href, or something arbitrary:

    <a data-href="/secret/landing/" class="btn btn--primary inline--block sign-in-button no--margin-b">Sign In</a>

    and then making the request via AJAX. So, if it aborted then we stay on the same page but if it's successful then you are taken to that page by means of a JavaScript redirect.

    This example is in CoffeeScript, because that is what I am using but the code is quite minimal and can be converted to JavaScript/jQuery as needed:

      secretSignInButtonClickHandler: (e) =>
        e.preventDefault()
    
        href = $(e.currentTarget).attr('data-href')
    
        $.ajax
          url: href
          success: (response) =>
            document.location = href
    

    Hope this helps someone.