|
function created(args) {
var grid = document.querySelector('#Grid').ej2_instances[0];
grid.dataSource = new DataManager({
adaptor: new ODataV4Adaptor(),
headers: [{ 'Authorization': 'bearertoken' }]
});
} |
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>