Search code examples
c#.net-coreautomationrestsharpweb-api-testing

How to add bearertoken to post/get restsharp automation testing


maybe anyone could help me with RestSharp api automation testing. I'll try to be as clear as possible.

Basically the scheme is: I'm sending my username/password credentials & I get BearerToken in return. I parse the bearer token into a json file.

After I get the bearer token I need to "Authenticate" in order to get the information that I need. For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";

        {

            var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");

            var request = new RestRequest(Method.GET);

            var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };

            request.AddJsonBody(body);


                var response = client.Post(request);
                HttpStatusCode statusCode = response.StatusCode;
                int numericStatusCode = (int)statusCode;


            request.AddHeader("content-type", "application/json");
            var queryResult = client.Execute<object>(request).Data;
            string jsonToken = JsonConvert.SerializeObject(queryResult);
            var JSON1 = JToken.Parse(jsonToken);
            var pureToken = JSON1.Value<string>("token");
            File.WriteAllText(@"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);

            Console.WriteLine(pureToken);
            Console.WriteLine(numericStatusCode)
    
The output I get is: token, status code 200 (correct credentials to get the bearertoken)

        //////////At this point I get the token and it is writed into my json file/////////////// (the token works)

Now im trying to authenticate with my token and get the company information that I need

            var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");

            var myRequest = new RestRequest(Method.POST);
            myRequest.AddHeader("Accept", "application/json");
            myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
            myRequest.AddHeader("content-type", "application/json");
            var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
            requestas.AddJsonBody(companyInfoInput);
            var response = myRequest.Execute(request);
            Console.WriteLine(response.Content);

The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.

    {"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}

What am I doing wrong? Any kind of help would be greatly appreciated!


Solution

  • In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:

    var authenticator = new JwtAuthenticator(pureToken);
    

    and then set your client authenticator like this:

    client.Authenticator = authenticator;
    

    Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.

    You can for example fix this statement:

    var myRequest = new RestRequest(url, DataFormat.Json);
    var response = client.Post(request);
    

    I also made this gist for you to check an example

    If you want to see something more complete I also have this another gist