Search code examples
c#asp.net-corerestsharp

RestSharp Returning Unauthorized in When making an API CAll


I am trying to make an api call to one of our internal services,

I am using RESTSharp.

Normally If I am using postman to call the service, I first generate a jwt token, then pass the token into the secured endpoint as a query param.

To replicate this in RestSharp, I did this:

 public async Task<string> GetAuthorizationToken(CancellationToken token)
 {
   var options = new RestClientOptions(_baseUrl);
   using var client = new RestClient(options)
   {

   };

   var request = new RestRequest(_resource)
     .AddParameter("client_id", _clientId)
     .AddParameter("client_secret", _clientSecret)
     .AddParameter("grant_type", _grantType)
     .AddParameter("password", _password)
     .AddParameter("username", _username);
   var response = await client.PostAsync<TokenResponseDto>(request);
   return response.Access_Token;
            
 }

then this is how I called the secured endpoint: the accesstoken is just jwt token.

        public async Task<CustomerResponseDto> GetCustomerDetailsByAccountNumber(CustomerRequestDto accountDetails, CancellationToken token)
        {
            var acccestoken = await GetAuthorizationToken(token);
            Console.WriteLine(acccestoken);
            accountDetails.AccountType = _acct_type;
            var options = new RestClientOptions(_baseUrl);
            using var client = new RestClient(options)
            {
                
            };
            var request = new RestRequest(_customer_resource)
                .AddParameter("access_token", acccestoken)
                .AddHeader("Content-Type", "application/json")
                .AddHeader("Accept", "application/json")
                .AddJsonBody(accountDetails);
            var response = await client.PostAsync<CustomerResponseDto>(request);

            return response;
        }

this is a sample url of how I called it in postman and It worked, it returned the records as expected

http://x.x.x.x:{port}/{service}/secured/{customer_resource}?access_token={auth_token}

I have tried all the things I could yet no solution.

Additional Information:

  1. This is the constructor for the Class
  2. Note the jwt token generates
        public CustomerRespository(string clientId, string acctstmresource, string customer_resource, string clientSecret, string grantType, string password, string username, string baseUrl, string resource, string baseUrl2, string correlationId, string xclient, string resource2, string bankcode, string acct_type)
        {
            _clientId = clientId;
            _clientSecret = clientSecret;
            _grantType = grantType;
            _password = password;
            _username = username;
            _baseUrl = baseUrl;
            _resource = resource;
            _baseUrl2 = baseUrl2;
            _correlationId = correlationId;
            _xclient = xclient;
            _resource2 = resource2;
            _bankcode = bankcode;
            _acctstmresource = acctstmresource;
            _customer_resource = customer_resource;
            _acct_type = acct_type;

        }

Error Message:

Request Failed with status Unauthorized

Stack Trace:

   at RestSharp.RestClientExtensions.<PostAsync>d__16`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CCMP.Persistence.Repositories.CustomerRespository.<GetCustomerDetailsByAccountNumber>d__17.MoveNext() in E:\source\repos\CCMP-API\CCMP.Persistence\Repositories\CustomerRespository.cs:line 83
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CCMP.Application.Services.CustomerService.<GetCustomer>d__3.MoveNext() in E:\source\repos\CCMP-API\CCMP.Application\Services\CustomerService.cs:line 27

Kindly Help This is my fisrt time using RestSharp.


Solution

  • When using AddParameter, you add a so-called Get or Post parameter. When you use POST, it will be added to the request body, and you want it to be a part of the query.

    You need to use the following:

    var request = new RestRequest(_customer_resource)
        .AddQueryParameter("access_token", acccestoken)
        .AddJsonBody(accountDetails);
    

    You don't need to manually add Content-Type and Accept headers, RestSharp does it for you.