Sina Hwz Sina Hwz - 20 days ago 7
AngularJS Question

in AngularJS, JWT Authorization header is undefined

I am trying to access an api using jwt. When I post with credentials, I get the

id_token
from server. I extract it, but when I try to add the token to the next requests in
Authorization header
using
Bearer
, the token is shown as
undefined
, therefor receiving the 500 Internal Error as "JWT strings must contain exactly 2 period characters. Found: 0". The console error is shown in the picture

My code is as following:

angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
method : "POST",
url : "http://server.com/api/authenticate",
data: '{"username":"username","password":"password","rememberMe":true}',
headers:{"Content-Type": "application/json;charset=UTF-8",
}
}).then(
function mySuccess(response){
$scope.token = response.data.id_token;
}, function myError(response){
console.log(response);
});

$http({
method: "GET",
url: "http://server.com/api/account",
data: '',
headers:{"Authorization": "Bearer " + $scope.token,
"Content-Type": "application/json;charset=UTF-8"}
}).then(
function mySuccess(response){
console.log(response);
}, function myError(response){
console.log(response);
});

});


enter image description here

Answer

Of course that happens because your token is returning AFTER your second request. On the fly you can solve it like this:

angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
    method : "POST",
    url : "http://server.com/api/authenticate",
    data: '{"username":"username","password":"password","rememberMe":true}',
    headers:{"Content-Type": "application/json;charset=UTF-8",
            }
    }).then(
    function mySuccess(response){
        $scope.token = response.data.id_token;
        $http({
            method: "GET",
            url: "http://server.com/api/account",
            data: '',
            headers:{"Authorization": "Bearer " + $scope.token,
                 "Content-Type": "application/json;charset=UTF-8"}
        }).then(
            function mySuccess(response){
                console.log(response);
            }, function myError(response){
                console.log(response);
            });

        });
    }, function myError(response){
        console.log(response);
    });