skip to Main Content

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?

2

Answers


  1. request.AddHeader("Authorization", $"Bearer {Token}");
    
    Login or Signup to reply.
  2. 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}");

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search