DevLayi
DevLayi

Reputation: 55

I'm getting error 401 (unauthorized) while trying to make a GET request from my API that has a JWT token

Here is my GETRequest method...

 HttpClient client = new HttpClient();
            var dashboardEndpoint = Helper.GetUsersurl;
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer"+Helper.userprofile.token);

            var result = await client.GetStringAsync(dashboardEndpoint);
            var UsersList = JsonConvert.DeserializeObject<AddedUsers>(result);
            //Users = new ObservableCollection<AddedUsers>(UsersList);

            Emplist.ItemsSource = UsersList.data;

        }

I've tried different method but the token isn't being sent alongside my request and therefore the API is throwing an error 401 at me. Any help will be gladly appreciated please...

Upvotes: 2

Views: 1001

Answers (2)

DevLayi
DevLayi

Reputation: 55

So, i later studied the pattern and also the response on postman then i realize I'm supposed to pass only the key and the value. In this context,

HttpClient client = new HttpClient();
            var dashboardEndpoint = Helper.GetUsersurl;
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", Helper.userprofile.token);

            var result = await client.GetStringAsync(dashboardEndpoint);
            var UsersList = JsonConvert.DeserializeObject<AddedUsers>(result);
            //Users = new ObservableCollection<AddedUsers>(UsersList);

            Emplist.ItemsSource = UsersList.data;

I only needed to pass Authorization as the key and token as the value. thanks everyone

Upvotes: 1

Agus Sapurta Sijabat
Agus Sapurta Sijabat

Reputation: 511

As @jason said, try to add a space between Bearer and the Token

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Helper.userprofile.token);

Upvotes: 0

Related Questions