Call upstream api with token from jQuery

We’re developing an aspnet core website with webapi backend all on a cloud platform. The auth part is implemented with openidconnect and cookies. Every tab is a new application to reduce release and test times. For the website / applications we have a razor class library that contains the main layout. See all posts in this series cloudnative

In Call upstream api with token we described how to get the token in the controller – the backend. Now we need to call the api from jQuery – the frontend. For this we implemented methods on the controller that can be called from jQuery. Because the request is for the samen site, the cookie is send with the request and the controller can access the token for us and do the upstream api request.

// controller = backend
public class RecordController : Controller {
  // other methods for aspnet core mvc like Index
 
  // called from frontend with jQuery
  [Authorize]
  public async Task<IActionResult> CallupstreamApi(
        [Required(AllowEmptyStrings = false)] string recordid)
  {
    if (!ModelState.IsValid) return BadRequest(ModelState);
    // call upstream api with IRestClient and recordid
    var request = new RestRequest("record/{id}");
    request.AddUrlSegment("id", recordid);
    var response = await _restClient.ExecuteAsync<record>(request, default);
    // return json for easy parsing in jQuery
    return Json(response.data);
  }
}
// index.cshtml = frontend
function RequestRecordFromUpstreamApi () {
  $.ajax({
    type: 'GET',
    url: '@Url.Action("CallupstreamApi")',
    datatype: 'json',
    data: { 
      recordid: 'my_id_for_record_1'
    },
    success: function (record) { console.log(record.id); },
    error: function (xhr, status, error) { console.log(xhr.responseText); }
  });
}
Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.