Home > Software engineering >  Using JWT Bearer Authentication When Call API
Using JWT Bearer Authentication When Call API

Time:10-03

I want to access an API for a purchased product, I used the following code according to the product documentation:

var client = new RestClient("http://example.com/api/login");

client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddParameter("username", "admin");
request.AddParameter("password", "admin");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The documentation says:

Authentication is performed via JWT Bearer Authentication. Every endpoint requires authentication, so you will need to add the following header to each request

Authorization: Bearer <JWT>

How can I add the JWT authentication in my upper request?

CodePudding user response:

Based on the Access Granted Client Credentials section of the documentation you've provided, the endpoint you need to be calling for a Bearer token is /admin/api/index.php/api/login.

Calling that endpoint with correct credentials will populate your response.Content with the below JSON:

{
  "status": 200,
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9kZW1vNC5zYXNyYWRpdXMuY29tXC9hZG1pblwvYXBpXC9pbmRleC5waHBcL2FwaVwvbG9naW4iLCJpYXQiOjE2MzA0MDU5OTgsImV4cCI6MTYzMDQwOTU5OCwibmJmIjoxNjMwNDA1OTk4LCJqdGkiOiJCZmdvN00zN2pkbGtRRzFhIiwic3ViIjoxLCJwcnYiOiJkNzk3N2M0N2U5MTY5NjUxMDEwNzM0ZDJmYmY4Y2MxMzlmM2U1MDM0In0.7tNWgF6psOPKpPC9-zU_hEK_GLx3-BeFlIW9LE4wzYo"
}

Deserialise the above JSON object to a token object & the token field will be your JWT token.

Token.cs

public class Token
{
    public int status { get; set; }
    public string token { get; set; }
}
var tokenObj = JsonConvert.DeserializeObject<Token>(response.Content);
string token = tokenObj.token;

For subsequent requests, to authenticate, add this line & you should be good to go.

request.AddHeader("Authorization", $"Bearer {token}");

CodePudding user response:

request.AddHeader("Authorization", $"Bearer {Token}");
  • Related