This is a migrated thread and some comments may be shown as answers.

Add Custom HTTP Header to JSON DataService

6 Answers 48 Views
ListBox
This is a migrated thread and some comments may be shown as answers.
Jason
Top achievements
Rank 2
Jason asked on 15 Aug 2018, 08:32 AM

I am trying to consume a JSON service for client-side data binding.

The service requires a JWT token to be included in a 'Authorization' http header.

I'm assuming i need to implement something on <ClientEvents OnDataBinding="">, but i have little idea where to start.             

Any help would be appreciated.

 

the dataservice is setup as follows

<DataService Location="http://localhost:39338/" DataPath="/list/notifications" EnableCaching="true" ResponseType="JSON" HttpMethod="Get" CountPropertyName="Count" DataPropertyName="Data" />

6 Answers, 1 is accepted

Sort by
0
Jason
Top achievements
Rank 2
answered on 15 Aug 2018, 03:25 PM

I got it working by doing the following

functiononDataBinding(sender, args) {
 
    $.ajaxSetup({
        'beforeSend': function (xhr) {
         xhr.setRequestHeader("Authorization", "Bearer BIGSECRET");
        }
    });
}

and then in the markup

<ClientEvents OnDataBinding="onDataBinding"  />

 

it works... not sure if it's best practice though.

0
Peter Milchev
Telerik team
answered on 20 Aug 2018, 07:04 AM
Hello Jason,

Thank you for sharing your solution with the community. 

Nevertheless, you should be cautious when using $.ajaxSetup because: "The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason, we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so."

That is why we recommend configuring the ajax settings per request. 

If you need further assistance with the configuration of the request, please share your whole configuration of the ListBox and data source you are using. 

Regards,
Peter Milchev
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Jason
Top achievements
Rank 2
answered on 23 Aug 2018, 09:05 AM

Hi Peter

Thanks for the response.

Could you possibly point me in the right direction for setting the header for this call only?

This is the full definition of the ListView

<telerik:RadListView
    id="lstNotifications"
    runat="server"   
    AllowPaging="true"
    PageSize="3"                    
    >
    <ClientSettings>
        <DataBinding ItemPlaceHolderID="items">
            <LayoutTemplate>
                <div id="items">
                </div>
            </LayoutTemplate>
            <ItemTemplate>
                <div id="div1" runat="server" class="dashboardNotificationContainer dashboardNotificationNormal">
                    <div class="dashboardNotificationRow">
                        <div class="dashboardNotificationCell"><strong>#= Title #</strong></div>
                    </div>
                    <div class="dashboardNotificationRow">
                        <div class="dashboardNotificationCell">#= Message #</div>
                    </div>
                    <div id="div2" runat="server" class="dashboardNotificationFooter"></div>
                    <div class="dashboardNotificationRow">
                        <div class="dashboardNotificationCell">#= Dashboard.formatDate(ValidFrom) #</div>
                        <div class="dashboardNotificationCell" style="float:right; text-transform:capitalize;">#= Dashboard.formatUserName(CreatedBy) #</div>
                    </div>
                </div>
            </ItemTemplate>
            <EmptyDataTemplate>
                <div class="NoContentTitleBar" >
                    <div class="NoContentTitleImage"><div class="ImageIcon32-Exclamation"></div></div>
                    <div class="NoContentTitle">No Notifications</div>
                </div>
                <div class="NoContent">       
                    There are currently no notifications that need your attention
                </div>
            </EmptyDataTemplate>
            <DataService Location="http://localhost:2211" DataPath="/ui/list/notifications" EnableCaching="false" ResponseType="JSON" HttpMethod="Get" CountPropertyName="Count" DataPropertyName="Data" />                                           
        </DataBinding>
        <ClientEvents OnDataBinding="Dashboard.addJWTTokenToHeader" />       
    </ClientSettings>
</telerik:RadListView>

 

and the javascript that adds the header

var Dashboard = Dashboard ||
{
    addJWTTokenToHeader: function (sender, args) {
        $.ajaxSetup({
            'beforeSend': function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer MYTOKEN");
            }
        });
    },
};

 

and some sample JSON that the service returns

{
   "Data":[
      {
         "SystemNotificationID":1,
         "Title":"Test",
         "Message":"Lorem ipsum dolor sit amet, eos at appetere vivendum mediocrem. Quot verterem pri ne, solum d....",
         "ValidFrom":"2018-08-01T00:00:00",
         "ValidTo":"2018-08-31T00:00:00",
         "DataPopulated":true,
         "AuditTrailPopulated":true,
         "Active":true,
         "Comment":""
      }
   ],
   "Count":1
}

 

If you need anything else, let me know.

 

0
Accepted
Peter Milchev
Telerik team
answered on 04 Sep 2018, 11:38 AM
Hello Jason,

Thank you for the further information. 

You can add the beforeSend handler in the AjaxSettings you receive in the OnListViewDataBinding event: 

function onListViewDataBinding(sender, args) {
    if (!args.get_ajaxSettings().beforeSend) {
        args.get_ajaxSettings().beforeSend = function (xhr) {
            xhr.setRequestHeader('customheader', 'custom header value');
        }
    }
}

This should add the authentication header similar to Add authentication request headers with ClientDataSource.

Regards,
Peter Milchev
Progress Telerik
0
Jason
Top achievements
Rank 2
answered on 14 Nov 2018, 10:59 AM

just thought I'd put my final solution here.

In the end i decided to use a RadClientDataSource

To add the custom http header, I implemented the OnRequestStart event as follows

var API = API || {};
API = API.Data ||
{
    addJWTTokenToHeader: function (xhr) {
        var token = 'some token value';
        xhr.setRequestHeader("Authorization", "Bearer " + token);
    },
 
    ClientDataSourceOnRequestStart: function (sender, eventArgs) {
        var transport = sender.get_dataSourceObject().options.transport;
        transport.read.beforeSend = API.Data.addJWTTokenToHeader;
    },
}
0
Jason
Top achievements
Rank 2
answered on 14 Nov 2018, 11:01 AM

Thanks to the assist Peter.

Important to note that the solution provided did work too :)

Tags
ListBox
Asked by
Jason
Top achievements
Rank 2
Answers by
Jason
Top achievements
Rank 2
Peter Milchev
Telerik team
Share this question
or