.netasp.net-web-apiidentityserver3nswag

How to invoke a NSwag client method that needs bearer token on request header?


I didn't get exactly how NSwag interact with IdentityServerX bearer tokens and adds it request header conventionally? My host api application implements IdentityServer3 with LDAP auth, so as far as i understand; if any host needs to a token for authentication then any client must send it on request header. So how can i deal with it while working NSwag clients ?

Any idea appreciated. Thanks.


Solution

  • I've resolved the issue by using a partial method e.g.

    CampaignClient.cs

    public partial class CampaignClient
    {
        partial void PrepareRequest(HttpClient request, ref string url);
    
        partial void ProcessResponse(HttpClient request, HttpResponseMessage response);
       
        // Some code...
    }
    

    CampaignClient.Extensions.cs - partial class:

    public partial class CampaignClient
    {
        private readonly IRequestContext _requestContext;
        private readonly IStartupConfiguration _startupConfiguration;
    
        public CampaignClient(IRequestContext requestContext, IStartupConfiguration startupConfiguration)
        {
            _requestContext = requestContext;
            _startupConfiguration = startupConfiguration;
        }
    
        partial void PrepareRequest(HttpClient request, ref string url)
        {
            request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _requestContext.GetBearerTokenOrTriggerUnauthException());
        }
    }
    

    Method override has saved me!