Failing to do a GET request after login

Viewed 177

Im very new to RestSharp and have been struggling with this for the last few days but the jist of it is I need to do a POST with a username and password, and obtain a bearer token to login to complete a series of requests. For this particular test its a GET to obtain a list of users.

Here is my code

 public void Authorization()
        {
            var client = new RestClient("https://url");
            var request = new RestRequest("api/auth/account/Login", Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddJsonBody(new { password = "TestPassword123!", username = "testuser@email.com" });
            var response = client.ExecutePostAsync(request).GetAwaiter().GetResult();

            var bearerToken = response.Content;
            var jwtAuth = new JwtAuthenticator(bearerToken);
            client.Authenticator = jwtAuth;

            var request2 = new RestRequest("/api/auth/Users", Method.GET);


            var response2 = client.ExecuteAsync(request2).GetAwaiter().GetResult();
            Console.WriteLine(response2.Content);
            Console.WriteLine(response2.ErrorException);
            Console.WriteLine(response2.ErrorMessage);
            Console.WriteLine(response2.Headers);
            Console.WriteLine(response2.IsSuccessful);
            Console.WriteLine(response2.StatusCode);
           
        }

I guess the problem im having is with Authentication and logging?.. when I run this my output is as follows

System.Collections.Generic.List`1[RestSharp.Parameter]
False
Unauthorized

The thing im confused about is when i print the bearerToken variable to the console its clearly my bearerToken in string format, what else would I need to do in order for the GET request following the post to go through?

Here is the postman screenshot of the GET request postman

Here is the postman screenshot of the POST request postman post request

1 Answers

While the code is running, have you tried to inspect the requests to see if the meta-data is correct and if Bearer Token is being added correctly? To do so, you can use a Debugging Proxy like https://www.telerik.com/fiddler

Update:I noticed you have a forward-slash ("/api") in your request2 endpoint string new RestRequest("/api/auth/Users", Method.GET); - see if taking that out makes a difference? In your first request, you dont have a slash

Update 2: I think I've figured it out! Try calling the Authenticate() method from JwtAuthenticator, so your code should look like:

var jwtAuth = new JwtAuthenticator(token);
jwt.Authenticate(client, request);
var request2 = new RestRequest("/api/auth/Users", Method.GET);

I found this out by looking at the JwtAuthenticator object - looks like it updates the Http Header for Authorization.

I can't immediately see what the issue is, someone else might, hope this helps

Related