Ares
Ares

Reputation: 101

Bearer Token in ajax request header undefined.

Here I am making a call to a controller method GetAccessTokenAsync it returns a JSON result containing the access token from auth0

function GetAccessToken() {
$.ajax({
    type: "GET",
    url: "https://localhost:44301/Account/GetAccessTokenAsync",
    contentType: 'json',
    dataType: 'json',
    success: function (data) {
        JSON.stringify(data)
    }
});}

Here is the controller method code

 public async Task<JsonResult> GetAccessTokenAsync()
    {
        var accessToken = await HttpContext.GetTokenAsync("access_token");

        return Json(accessToken);
    }

Here is where I am trying to get the value from the ajax call above into the request header but it keeps coming back undefined. However that call does contain the proper access token it just isn't setting it properly

function GetAll() {
var accessToken = GetAccessToken();
$.ajax({
    type: "GET",
    contentType: 'json',
    dataType: 'json',
    crossDomain: false,
    url: "https://localhost:44348/api/v1/trialuser/1",
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Bearer " + accessToken);
        request.setRequestHeader("Access-Control-Allow-Origin", "https://localhost:44301");
    },
    success: function (data) {
        $.each(data, function (key, item) {
            $('<tr>', { html: formatItem(item) }).appendTo($("#getAllTable"));
            $('#show').attr("disabled", true)
        })
    },

});}

Any one else have this issue? and my knowledge on jquery and ajax calls is not extensive so any examples is appreciated thanks

Upvotes: 0

Views: 2468

Answers (2)

front_end_dev
front_end_dev

Reputation: 2056

Change your GetAccessToken method to return response.

function GetAccessToken() {
$.ajax({
    type: "GET",
    url: "https://localhost:44301/Account/GetAccessTokenAsync",
    contentType: 'json',
    dataType: 'json',
    success: function (data) {
        return JSON.stringify(data)
    }
});}

Upvotes: 0

DiscipleMichael
DiscipleMichael

Reputation: 510

You're function GetAccessToken() does not return anything or set any global variable. So, your call to the function from the function GetAll() where you set accessToken = GetAccessToken() is setting nothing.

Either return something in the success event or set a variable value that both functions have access to the scope.

Upvotes: 1

Related Questions