angular-datatables icon indicating copy to clipboard operation
angular-datatables copied to clipboard

Unauthorized Requests

Open victorleal opened this issue 11 years ago • 9 comments

I'm using angular-datatables with server-side processing and Angular http interceptors to handle session expiring. It works with the requests made to the API normally, but the requests made by Datatables are not intercepted, and I just can't get any information from the server saying that the user has to log in again.

Instead, jQuery logs on the console a 401 error, but Angular does not catch it, and the application gets broken.

Any idea here? I think that a lot of people can have the same trouble, regarding that we use Angular with an API providing the data.

victorleal avatar Apr 16 '15 19:04 victorleal

Can you provide some code so I can try to reproduce your issue with my show case ?

l-lin avatar Apr 23 '15 14:04 l-lin

Sure!

$scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('ajax', {
            url: '/myApi/jsonData',
            type: 'GET',

            // I have to provide an error function here because the Angular Interceptors do not work with
            // this Ajax call.
            error: errorLoading
        })
        .withDataProp('data')
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withOption('createdRow', createdRow)
        .withBootstrap();

    $scope.dtColumns = [
        DTColumnBuilder.newColumn('id').withTitle('#ID'),
        DTColumnBuilder.newColumn('name').withTitle('Name'),
        DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable().withClass('actions').renderWith(actionsHtml)
    ];

And here are the Interceptors:

angular.module('apiInterceptor', [])

.factory('APIInterceptor', function($rootScope, $window) {

    var service = this;

    service.request = function(config) {
        console.log('request', config);
        return config;
    };

    service.requestError = function(config) {
        console.log('requestError', config);
        return config;
    };

    service.response = function(response) {
        console.log('response', response);
        return response;
    };

    service.responseError = function(response) {
        console.log('responseError', response);
        return response;
    };

    return service;

});

They are pushed through the $httpProvider on the app config function: $httpProvider.interceptors.push('APIInterceptor');

Maybe the interceptors should not work beacuse they're attached to the $httpProvider, and Datatables does not use it to make the Ajax calls, but I'm not sure about it.

victorleal avatar Apr 23 '15 15:04 victorleal

@victorleal - Were you able to solve this issue? I am also struggling with the exact same problem. I understand that $httpProvider will not work in this case, but definitely need support in angular datatables to pass APIInterceptor to the request.

vinayagarwal avatar May 19 '15 05:05 vinayagarwal

@vinayagarwal I didn't solve this issue. I'm not using Angular anymore for the project, but the solution was using a specific error function to the Ajax call of Datatables. So, I was unable to handle the requests through APIInterceptor.

victorleal avatar May 19 '15 12:05 victorleal

I'm having the exact same trouble and I want to skip the error handling of Datatables when status code is 401. How to do it?

ahmadhsalim avatar Oct 31 '15 13:10 ahmadhsalim

Hehe, putting angular aside seems a little drastic measure, victor! :-p I had a similar issue, where I wanted to change from the angular way to the ajax renderer with serverside processing and since the oauth token refresh was being handled the the $httpProvider interceptors, it was not an option to get rid of them! So one way to work with it is using the fnServerData function (.withServerData() in DTOptionsBuilder) where I convert the datatable ajax request to an $http config object and use the $http service to get the data instead! Maybe not the best way, but still a way to keep using your interceptors!

DTOptionsBuilder.newOptions().withFnServerData(
    function(sSource, aoData, fnCallback, oSettings){
        // convert the stuff you get in aoData to an $http config object
        var config = ...

        $http(config)
            .then(function(response) {
                //do data manipulation here to make it look like an ajax response
                var results = {
                    draw: ...,
                    recordsTotal: ...,
                    recordsFiltered: ...,
                    data: response
                };
                fnCallback(results);
            });
   }
);

RuiDores avatar Jan 20 '16 10:01 RuiDores

@RuiDores Yes, putting Angular aside is really a drastic measure! But, at that moment, we were doing just a proof of concept... It was just a draft.

We are still using Angular, but just to do some interaction and keep the code organized.

Your solution sounds good! Maybe I can try it in another project!

victorleal avatar Jan 20 '16 11:01 victorleal

I managed to solve this issue including the token inside the authorization header and adding an error function to be called if the request fails.

.withOption('ajax', {
    headers: {
        Authorization: 'Bearer ' + localStorage.getItem('satellizer_token')
    },
    dataSrc: 'data',
    url: url,
    type: 'GET',
    error: function () {
        // remove the token from localStorage and redirect to the auth state
    }
})

Please let me know if this also works for you.

rcevs avatar Apr 14 '16 20:04 rcevs

Based on rcevs correct answer, you can simply intercept a response (via $httpProvider) like this:

.withOption('ajax', {
                dataSrc: 'items',
                type: 'GET',
                url: configService.getConfig()._links.locationsDatatable.href,
                headers: { ... },
                data: function(data) {
                    simplifyDatatableQuery(data);
                },
                error: function (response) {
                    errorHandlerService.handleResponseError(response);
                }
            })

where errorHandlerService.handleResponseError is simple method in service:

errorService.handleResponseError=function(response) {
            switch (response.status) {
                case 403:
                    $location.url('/forbidden');
                    break;
                case 500:
                    whatever you want...
                    break;
            }
            $q.reject(response);
        };

tslavik avatar Jul 14 '16 15:07 tslavik