http basic authentication “log out”

前端 未结 8 1338
悲&欢浪女
悲&欢浪女 2020-11-28 04:23

HTTP basic authentication credentials are stored until the browser is closed, but is there a way to remove the credentials before the browser is closed?

I read about

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 04:43

    Expanding on Jan.'s answer, and updating owyongsk's answer:

    Here is some example jquery java-script code to cause the browser to essentially send a bogus login request to the page your trying to protect, which in all tested browsers caused the cached credentials to be removed, then redirects the user to a non-protected page.

    The alert() when something goes wrong should probably be changed to something else.

    //Submits an invalid authentication header, causing the user to be 'logged out'
    function logout() {
        $.ajax({
            type: "GET",
            url: "PUT_YOUR_PROTECTED_URL_HERE",
            dataType: 'json',
            async: true,
            username: "some_username_that_doesn't_exist",
            password: "any_stupid_password",
            data: '{ "comment" }'
        })
    //In our case, we WANT to get access denied, so a success would be a failure.
    .done(function(){
        alert('Error!')
    })
    //Likewise, a failure *usually* means we succeeded.
    //set window.location to redirect the user to wherever you want them to go
    .fail(function(){
        window.location = "/";
        });
    }
    

    Then it was as easy as just having the logout link call the logout() function, and it seemed to work seamlessly to the user, though it is still technically a hack job.

提交回复
热议问题