MB_18
MB_18

Reputation: 2239

How to use access tokens to get authorization to access REST APIs

I have an HttpClient that I am using for a REST API. I get the access token from the server but I do not have permission to use the REST APIs. The response is Error: Unauthorized

First, Using getAccessToken() method, I get the access token.

   public static async Task<string> getAccessToken()
    {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Referer", "http://admin.altrabo.com/");

            var tokenClient = new TokenClient()
            {
              client_Id= -1,
              username= "admin",
              password= "Main@dm!n",
              grant_Type= "Main@dm!n",
              externalProvider= 1,
 
            };

            HttpResponseMessage response = await client.PostAsJsonAsync<TokenClient>("https://api.altrabo.com/api/v1/token", tokenClient);
            var json = JsonSerializer.Deserialize<AccessToken>(response.Content.ReadAsStringAsync().Result);
            return json.access_token;
   }

which returns the access token.

Then, using the verifyToken() method, I verify the access token.

public static async Task<string> verifyToken(string access_token)
{
  var client = new HttpClient();
  client.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
  HttpResponseMessage response = await client.GetAsync("https://api.altrabo.com/api/v1/verifyToken");
  return response.ReasonPhrase;          
}

returns OK

But when I want to get access to API, I encounter Error: Unauthorized.

For example when I want to get the list of airports:

public static async Task<string> ListAirports()
{
    var client = new HttpClient();
    return await client.GetStringAsync("https://api.altrabo.com/api/v1/BaseData/GetAirports?pageSize=1000&pageNumber=1");
}

The API documentation is available at https://www.getpostman.com/collections/51cd9e7f5f6ebafa8c48‎

Upvotes: 2

Views: 10199

Answers (2)

Lars Kristensen
Lars Kristensen

Reputation: 1495

Add the token to the request to get the airports, in the same manner you do, as when you verify the token.

public static async Task<string> ListAirports(string access_token)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
    return await client.GetStringAsync("https://api.altrabo.com/api/v1/BaseData/GetAirports?pageSize=1000&pageNumber=1");
}

Upvotes: 6

Maxi
Maxi

Reputation: 31

you have to check the documentation of the rest-api for what authorization-method the api requires. Maybe its username/password or something.

https://username:[email protected]

Upvotes: 0

Related Questions