How do I add an authorization token to a datagrid which is accessing data using OData

Good day

I am using a datagrid to maintain tabular data using IdentityServer for authentication. I have been unable to locate the documentation which indicates how to send the authorization token in the datamanager of the grid.

Can you please assist 

Thanks

Ronald


<div>

    <ejs-grid id="Grid" toolbar="@(new List<string>() { "Add", "Edit", "Delete" })" allowPaging="true" allowSorting="true" allowFiltering="true" actionFailure="actionFailure" created="created" actionComplete="complete">
        <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog"></e-grid-editSettings>
        <e-grid-pagesettings pageSize="7">
        </e-grid-pagesettings>
        <e-grid-columns>
            <e-grid-column field="ID" headerText="ID" visible="false" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column>
            <e-grid-column field="Code" headerText="Code" width="150"></e-grid-column>
            <e-grid-column field="ShortDescription" headerText="Short Description" width="150"></e-grid-column>
            <e-grid-column field="LongDescription" headerText="Long Description" width="170"></e-grid-column>
        </e-grid-columns>
    </ejs-grid>


</div>
<script>
    function actionFailure(args) {
        console.log(args);
        var span = document.createElement('span');
        this.element.parentNode.insertBefore(span, this.element);
        span.style.color = '#FF0000'
        span.innerHTML = 'Server exception: 404 Not found';
    }
</script>


<script>
    function created(args) {
        var grid = document.querySelector('#Grid').ej2_instances[0];
        grid.dataSource = new ej.data.DataManager({
            url: "@Configuration["ApiResourceBaseUrls:Api"]/odata/TableCollections",
            adaptor: new ej.data.ODataV4Adaptor({ updateType: 'PUT' })

        });
    }
</script>

<script type="text/javascript">
    function complete(args) {
        if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
            let dialog = args.dialog;
            // change the header of the dialog
            dialog.header = args.requestType === 'beginEdit' ? 'Edit Record' : 'New Record';
        }
    }

</script>

3 Replies 1 reply marked as answer

VS Vignesh Sivagnanam Syncfusion Team September 22, 2020 01:55 PM UTC

Hi Ronald 

Based on your query we suspect that you need to send the authorization token using the DataManager. To achieve this we suggest you to use the headers property of the DataManager. 

Please refer the below code example: 

Code Snippet : 
function created(args) { 
        var grid = document.querySelector('#Grid').ej2_instances[0]; 
        grid.dataSource = new DataManager({ 
            adaptor: new ODataV4Adaptor(), 
            headers: [{ 'Authorization': 'bearertoken' }] 
        }); 
    } 
 
Please refer the below documentation for your reference, 


Please get back to us if you require any further assistance. 

Regards, 
Vignesh Sivagnanam 


Marked as answer

RW Ronald Walcott September 23, 2020 02:30 AM UTC

Thanks. I got it to work.

For anybody else doing this with ASP .NET Core these are the complete steps that I followed

Create an interface

using System.Threading.Tasks;

 

namespace MVCClient.Services

{

    public interface IAuthToken

    {

        Task<string> GetToken();

    }

}

Implement it

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Http;

using Microsoft.IdentityModel.Protocols.OpenIdConnect;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace MVCClient.Services

{

    public class AuthToken : IAuthToken

    {

        private readonly IHttpContextAccessor _httpContextAccessor;

 

        public AuthToken(IHttpContextAccessor httpContextAccessor)

        {

            _httpContextAccessor = httpContextAccessor;

        }

 

        public async Task<String> GetToken()

        {

            var accessToken = await _httpContextAccessor

                .HttpContext

                .GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

 

 

            return accessToken;

        }

    }

}

 

Configure dependency injection, add to Startup.cs

services.AddScoped<IAuthToken, AuthToken>();

Inject into the view controller

    public class CollectionController : Controller

    {

        private readonly IAuthToken _authToken;

 

        public CollectionController(IAuthToken authToken)

        {

            _authToken = authToken;

        }

 

        public async Task<IActionResult> Index()

        {

            String token = await  _authToken.GetToken();

            ViewBag.AuthToken = token;

            return View();

        }

Use a viewbag to pass the token to the view

Modify the grid in the index view by adding a header to the datamanager source

<script>

    function created(args) {

        var grid = document.querySelector('#Grid').ej2_instances[0];

        grid.dataSource = new ej.data.DataManager({

            url: "@Configuration["ApiResourceBaseUrls:Api"]/odata/TableCollections",

            adaptor: new ej.data.ODataV4Adaptor({ updateType: 'PUT' }),

            headers: [{ 'Authorization': 'Bearer ' + '@ViewBag.AuthToken' }]

        });

    }

</script>





VS Vignesh Sivagnanam Syncfusion Team September 24, 2020 03:28 PM UTC

Hi Ronald, 

Thank you for sharing the information and code. 

We are glad that your issue has been fixed. 

Regards, 
Vignesh Sivagnanam 


Loader.
Up arrow icon