Preventing HTTP Basic Auth Dialog using AngularJS Interceptors

前端 未结 3 946
我在风中等你
我在风中等你 2020-12-15 17:54

I\'m building an AngularJS (1.2.16) web app with a RESTful API, and I\'d like to send 401 Unauthorized responses for requests where authentication information is invalid or

3条回答
  •  猫巷女王i
    2020-12-15 18:26

    For future reference

    I've come up with this solution when trying to handle 401 errors. I didn't have the option to rewrite Basic to x-Basic or anything similar, so I've decided to handle it on client side with Angular.

    When initiating a logout, first try making a bad request with a fake user to throw away the currently cached credentials.

    I have this function doing the requests (it's using jquery's $.ajax with disabled asynch calls):

    function authenticateUser(username, hash) {
        var result = false;
        var encoded = btoa(username + ':' + hash);
    
        $.ajax({
            type: "POST",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Basic ' + encoded);
            },
            url: "user/current",
            statusCode: {
                401: function () {
                    result = false;
                },
                200: function (response) {
                    result = response;
                }
            },
            async: false
        });
    
        return result;
    }
    

    So when I try to log a user out, this happens:

    //This will send a request with a non-existant user.
    //The purpose is to overwrite the cached data with something else
    accountServices.authenticateUser('logout','logout');
    
    //Since setting headers.common.Authorization = '' will still send some
    //kind of auth data, I've redefined the headers.common object to get
    //rid of the Authorization property
    $http.defaults.headers.common = {Accept: "application/json, text/plain, */*"};
    

提交回复
热议问题