{"id":95019,"date":"2023-09-08T08:17:32","date_gmt":"2023-09-08T06:17:32","guid":{"rendered":"https:\/\/code-maze.com\/?p=95019"},"modified":"2023-09-08T09:54:16","modified_gmt":"2023-09-08T07:54:16","slug":"aspnetcore-basic-authentication-with-httpclient","status":"publish","type":"post","link":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/","title":{"rendered":"How to Use Basic Authentication With HttpClient?"},"content":{"rendered":"<p>In this article, we are going to discuss how to use basic authentication with HttpClient. While the topic may seem straightforward, there are a few different ways to solve this problem. We&#8217;ll try and cover some of the main approaches, and hopefully, by the end, we will know which approach is best and why.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/authorization-dotnet\/BasicAuthenticationWithHttpClient\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Before we dive into the code, it&#8217;s always helpful to set some context on the problem itself.<\/p>\n<h2>What Is Basic Authentication?<\/h2>\n<p>When we are trying to protect some resources (for example, an operation on a backend API, or maybe access to some data), we require some <a href=\"https:\/\/code-maze.com\/http-authentication\/\" target=\"_blank\" rel=\"noopener\">kind of authentication<\/a> to secure this access. This requires the consumer to identify themselves to the target server, to gain access to the resource it requires. It does this via the <code>Authorization<\/code> header in the HTTP Request.<\/p>\n<p>A sample Basic Authentication header might look like this:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=<\/code><\/p>\n<p>The value comprises the word Basic (to identify the scheme), followed by a space, followed by a Base-64 encoded value of a username\/password combination, in the format of <code>username:password<\/code>.\u00a0<\/p>\n<h3>Comparing Basic Authentication to Other Authentication Schemes<\/h3>\n<p>Since Base-64 is a very simple algorithm with no encryption which is easy to reverse, any attacker could easily figure out the username and password and issue that same request to gain access. Furthermore, since the credential is passed in every request, it&#8217;s very simple for an attacker to impersonate the real user.\u00a0<\/p>\n<p>If we contrast this to the more popular method of OAuth, all these problems are solved. <strong>Therefore, if we are trying to secure applications over the public internet, it&#8217;s generally preferred to use OAuth or some other style of token-based authentication<\/strong>.<\/p>\n<p>It&#8217;s important to always understand the limitations of the practices we apply, so we can make an informed judgment choice. Now that we understand those limitations, let&#8217;s move on and see how to apply basic authentication in .NET with <code>HttpClient<\/code>.<\/p>\n<h2>Building the Server<\/h2>\n<p>To demonstrate basic authentication, we require a client and server. To show this in its simplest form, we&#8217;ll create the server and client as separate ASP.NET Core APIs. But in reality, the applications can be anything that can deal with HTTP, as that&#8217;s the protocol for basic authentication security.<\/p>\n<p>Let&#8217;s start with the server, by creating a standard ASP.NET Core API with Controllers, calling it &#8220;Server&#8221; and adding a method called <code>IsRequestAuthenticated()<\/code>:<\/p>\n<div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private bool IsRequestAuthenticated()\r\n{\r\n    try\r\n    {\r\n        if (AuthenticationHeaderValue.TryParse(Request.Headers.Authorization, \r\n                                               out var basicAuthCredential))\r\n        {\r\n            if (basicAuthCredential.Scheme == \"Basic\" &amp;&amp;\r\n                !string.IsNullOrWhiteSpace(basicAuthCredential.Parameter))\r\n            {\r\n                var usernamePassword = \r\n                    Encoding.UTF8.GetString(Convert.FromBase64String(basicAuthCredential.Parameter));\r\n                if (!string.IsNullOrWhiteSpace(usernamePassword))\r\n                {\r\n                    var separatorIndex = usernamePassword.IndexOf(':');\r\n\r\n                    var username = usernamePassword[..separatorIndex];\r\n                    var password = usernamePassword[(separatorIndex+ 1)..];\r\n\r\n                    if (username == \"codemaze\" &amp;&amp;\r\n                        password == \"isthebest\")\r\n                    {\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    catch\r\n    {\r\n        \/\/logic for catching exceptions here\r\n    }\r\n\r\n    return false;\r\n}<\/pre>\n<p>There&#8217;s a lot going on in the code, but essentially we are getting the value from the header, decoding it, and ensuring it matches the username-password combination we expect. If it does, we return true. Otherwise, false.<\/p>\n<p>Now let&#8217;s modify the existing <code>Get()<\/code> method to make use of our new method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet]\r\npublic IActionResult Get()\r\n{\r\n    if (IsRequestAuthenticated())\r\n    {\r\n        return Ok(Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast\r\n        {\r\n            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),\r\n            TemperatureC = Random.Shared.Next(-20, 55),\r\n            Summary = Summaries[Random.Shared.Next(Summaries.Length)]\r\n        }));\r\n    }\r\n    \r\n    return Unauthorized();            \r\n}<\/pre>\n<p>It&#8217;s very straightforward: if the request is authenticated we allow it through, otherwise, we return Unauthorized (401).<\/p>\n<p>We should note there are much cleaner ways to this approach.<\/p>\n<p><strong>First, we should set up some middleware to run on every request so that we don&#8217;t need to repeat ourselves and keep the authentication code separate from our logic<\/strong>. After that, there are several NuGet packages available that can do all this heavy lifting for us and improve some of our security logic.<\/p>\n<p>However, since we are just demonstrating the concept here, this code is fine.<\/p>\n<h3>Testing Basic Authentication on the Server<\/h3>\n<\/div>\n<p>Let&#8217;s hit the endpoint in Postman with no additional headers to observe the result and ensure that our server is secured as we expect:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/01-Server-Secure.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-95025 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/01-Server-Secure.png\" alt=\"Server with Basic Authentication Enabled\" width=\"896\" height=\"518\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/01-Server-Secure.png 896w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/01-Server-Secure-300x173.png 300w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/01-Server-Secure-768x444.png 768w\" sizes=\"auto, (max-width: 896px) 100vw, 896px\" \/><\/a><\/p>\n<p>As we expected, we got an <code>401 Unauthorized<\/code> response.<\/p>\n<p>Let&#8217;s now set the <code>Authorization<\/code> header with the value of <code>Basic Y29kZW1hemU6aXN0aGViZXN0<\/code> (which is the Base-64 encoded representation of <code>codemaze:isthebest<\/code>):<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/02-Successful-Postman-Request-With-Basic-Authentication.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-95024 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/02-Successful-Postman-Request-With-Basic-Authentication.png\" alt=\"Successful Request With Basic Authentication\" width=\"892\" height=\"553\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/02-Successful-Postman-Request-With-Basic-Authentication.png 892w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/02-Successful-Postman-Request-With-Basic-Authentication-300x186.png 300w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/02-Successful-Postman-Request-With-Basic-Authentication-768x476.png 768w\" sizes=\"auto, (max-width: 892px) 100vw, 892px\" \/><\/a><\/p>\n<p>This time the request was successful, and we get a <code>200 OK<\/code> status code and the response we expected.<\/p>\n<p>We have a server protected with basic authentication. Now it&#8217;s time to set up the client to communicate with it.<\/p>\n<h2>Building the Client<\/h2>\n<p>Let&#8217;s add another project to our solution, again an ASP.NET Core API, this time let&#8217;s call it &#8220;Client&#8221;. Let&#8217;s modify the <code>WeatherForecastController<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using Microsoft.AspNetCore.Mvc;\r\n\r\nnamespace Client.Controllers;\r\n\r\n[ApiController]\r\n[Route(\"[controller]\")]\r\npublic class WeatherForecastController : ControllerBase\r\n{\r\n    private static readonly HttpClient _httpClient = new HttpClient();\r\n\r\n    public WeatherForecastController()\r\n    {\r\n        _httpClient.BaseAddress = new Uri(\"https:\/\/localhost:7003\");\r\n    }\r\n\r\n    [HttpGet]\r\n    public async Task&lt;IActionResult&gt; Get()\r\n    {\r\n        var response = await _httpClient.GetStringAsync(\"weatherforecast\");\r\n\r\n        return Content(response, \"application\/json\");\r\n    }\r\n}<\/pre>\n<p>The most notable aspect of our code is the use of <code>HttpClient<\/code>, which is the preferred way to interact with remote services over HTTP.<\/p>\n<p>As we demonstrate in our <a href=\"https:\/\/code-maze.com\/fetching-data-with-httpclient-in-aspnetcore\/\" target=\"_blank\" rel=\"noopener\">Fetching Data and Content Negotiation with HttpClient in ASP.NET Core<\/a> article, we create a static instance of <code>HttpClient<\/code>, set the base address in the constructor then call out to it in our <code>Get()<\/code> method. Because we know the response is JSON (when successful), we can use the convenient <code>GetStringAsync()<\/code> method, and instead of trying to deserialize again into a model, we can return it straight back.\u00a0<\/p>\n<p>Let&#8217;s see what happens if we execute our <code>Get()<\/code> route in Postman:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-95023 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2.png\" alt=\"Failing Client Request Without Basic Authentication\" width=\"809\" height=\"810\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2.png 809w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2-300x300.png 300w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2-150x150.png 150w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2-768x769.png 768w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2-75x75.png 75w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/03-Failing-Client-Request-Without-Basic-Authentication-2-440x440.png 440w\" sizes=\"auto, (max-width: 809px) 100vw, 809px\" \/><\/a><\/p>\n<p>The client code crashes, returning\u00a0 a <code>500 Internal Server Error<\/code>, because it received a <code>401 Unauthorized<\/code> error. We expect this, as, of course, we didn&#8217;t set the header.<\/p>\n<div style=\"padding: 20px; border-left: 5px gray solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">Note: Exposing the raw exception details in production environments is not the best way to deal with errors on an API. For more details on how to approach this, check out our article on the <a href=\"https:\/\/code-maze.com\/using-the-problemdetails-class-in-asp-net-core-web-api\/\" target=\"_blank\" rel=\"noopener\">ProblemDetails<\/a> class.<\/div>\n<p>There are a few ways to do this, let&#8217;s start with the manual way.<\/p>\n<h3>Setting the Basic Authentication Header<\/h3>\n<p>Let&#8217;s modify our <code>Get()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4-5\">[HttpGet]\r\npublic async Task&lt;IActionResult&gt; Get()\r\n{\r\n    _httpClient.DefaultRequestHeaders.Clear();\r\n    _httpClient.DefaultRequestHeaders.Add(\"Authorization\", \"Basic Y29kZW1hemU6aXN0aGViZXN0\");\r\n\r\n    var response = await _httpClient.GetStringAsync(\"weatherforecast\");\r\n\r\n    return Content(response, \"application\/json\");\r\n}<\/pre>\n<p>Because we know the value it needs to be, we can simply hardcode it in the <code>Authorization<\/code> header. If we run the request again, we see it succeeds and we receive the response we expect:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/04-Successful-Client-Request-With-Basic-Authentication-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-95022 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/04-Successful-Client-Request-With-Basic-Authentication-1.png\" alt=\"Successful Client Request With Basic Authentication\" width=\"894\" height=\"551\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/04-Successful-Client-Request-With-Basic-Authentication-1.png 894w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/04-Successful-Client-Request-With-Basic-Authentication-1-300x185.png 300w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/08\/04-Successful-Client-Request-With-Basic-Authentication-1-768x473.png 768w\" sizes=\"auto, (max-width: 894px) 100vw, 894px\" \/><\/a><\/p>\n<p>However, this code has several issues. <strong>If the username or password changes, we need to re-generate the Base-64 encoded value external to this app and redeploy it. Moreover, we should avoid embedding security credentials in code and source control<\/strong>.<\/p>\n<p>Let&#8217;s look to improve these issues.<\/p>\n<h3>Improving the Basic Authentication Logic<\/h3>\n<p>Let&#8217;s first look at securing the credential. Right-click on our project and select &#8220;Manage User Secrets&#8221;, and add a couple of values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"BasicAuthenticationUsername\": \"codemaze\",\r\n  \"BasicAuthenticationPassword\": \"isthebest\"\r\n}<\/pre>\n<p><a href=\"https:\/\/code-maze.com\/aspnet-configuration-securing-sensitive-data\/\" target=\"_blank\" rel=\"noopener\">User Secrets<\/a> are a great way to keep sensitive values out of code and source control. If we wanted to deploy this somewhere, for example, Azure App Service, we could leverage something like Azure Key Vault. However, for our example here, this is perfectly secure.<\/p>\n<p>Let&#8217;s modify our code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4-11\">[HttpGet]\r\npublic async Task&lt;IActionResult&gt; Get()\r\n{\r\n    var basicAuthenticationUsername = _configuration[\"BasicAuthenticationUsername\"];\r\n    var basicAuthenticationPassword = _configuration[\"BasicAuthenticationPassword\"];\r\n    var basicAuthenticationValue = \r\n        Convert.ToBase64String(\r\n            Encoding.ASCII.GetBytes($\"{basicAuthenticationUsername}:{basicAuthenticationPassword}\"));\r\n\r\n    _httpClient.DefaultRequestHeaders.Clear();\r\n    _httpClient.DefaultRequestHeaders.Add(\"Authorization\", $\"Basic {basicAuthenticationValue}\");\r\n\r\n    var response = await _httpClient.GetStringAsync(\"weatherforecast\");\r\n    \r\n    return Content(response, \"application\/json\");\r\n}<\/pre>\n<p>This time we are reading the values from the configuration, and applying them at runtime. <strong>This means if the values change, all we need to do is update the secrets and restart the app. No redeployment is necessary.<\/strong> Note we could also use a <a href=\"https:\/\/code-maze.com\/aspnetcore-read-appsettings-values-from-a-json-file\/\" target=\"_blank\" rel=\"noopener\">strongly-typed configuration<\/a> instead of dealing with <code>IConfiguration<\/code> directly which is the preferred way, but that is outside the scope of this article.<\/p>\n<p>We can simplify our code that sets the header even further:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"10-11\">[HttpGet]\r\npublic async Task&lt;IActionResult&gt; Get()\r\n{\r\n    var basicAuthenticationUsername = _configuration[\"BasicAuthenticationUsername\"];\r\n    var basicAuthenticationPassword = _configuration[\"BasicAuthenticationPassword\"];\r\n    var basicAuthenticationValue = \r\n        Convert.ToBase64String(\r\n            Encoding.ASCII.GetBytes($\"{basicAuthenticationUsername}:{basicAuthenticationPassword}\"));\r\n\r\n    _httpClient.DefaultRequestHeaders.Authorization = \r\n        new AuthenticationHeaderValue(\"Basic\", basicAuthenticationValue);\r\n\r\n    var response = await _httpClient.GetStringAsync(\"weatherforecast\");\r\n\r\n    return Content(response, \"application\/json\");\r\n}<\/pre>\n<p>This is cleaner as we don&#8217;t need to clear the default headers or perform string manipulation in the value.<\/p>\n<p>Everything is working great!<\/p>\n<p>However there is one more problem with our code, and that is the use of <code>HttpClient<\/code> itself. In the next section let&#8217;s look at why.<\/p>\n<h3>Correct Use of HttpClient<\/h3>\n<p>In our code, we are creating a static instance of <code>HttpClient<\/code>. <strong>This exposes several issues, including DNS caching issues, repeating configuration code and incorrectly disposing of resources to name a few<\/strong>. It&#8217;s tempting to make use of <code>using<\/code> statements to combat this problem, but then we will create even more <code>HttpClient<\/code> instances and run into socket exhaustion issues.<\/p>\n<p>There is a better way that solves all these problems, and that is with the use of <code>HttpClientFactory<\/code>. We cover this in detail in our <a href=\"https:\/\/code-maze.com\/using-httpclientfactory-in-asp-net-core-applications\/\" target=\"_blank\" rel=\"noopener\">Using HttpClientFactory in ASP.NET Core Applications<\/a> article, so let&#8217;s jump right into how to apply it here.<\/p>\n<p>First, let&#8217;s create a class <code>WeatherForecastClient<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using System.Net.Http.Headers;\r\nusing System.Text;\r\n\r\nnamespace Client;\r\n\r\npublic class WeatherForecastClient\r\n{\r\n    private readonly HttpClient _httpClient;\r\n\r\n    public WeatherForecastClient(HttpClient httpClient, IConfiguration configuration)\r\n    {\r\n        _httpClient = httpClient;\r\n        _httpClient.BaseAddress = new Uri(\"https:\/\/localhost:7003\");\r\n        var basicAuthenticationUsername = configuration[\"BasicAuthenticationUsername\"];\r\n        var basicAuthenticationPassword = configuration[\"BasicAuthenticationPassword\"];\r\n        var basicAuthenticationValue = \r\n            Convert.ToBase64String(\r\n                Encoding.ASCII.GetBytes($\"{basicAuthenticationUsername}:{basicAuthenticationPassword}\"));\r\n        _httpClient.DefaultRequestHeaders.Authorization = \r\n            new AuthenticationHeaderValue(\"Basic\", basicAuthenticationValue);\r\n    }\r\n\r\n    public async Task&lt;string&gt; GetAsync() =&gt; await _httpClient.GetStringAsync(\"weatherforecast\");\r\n}\r\n<\/pre>\n<p>This is all the logic we previously had in our <code>Get()<\/code> method.\u00a0<\/p>\n<p>Let&#8217;s add a line to our <code>Program.cs<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddHttpClient&lt;WeatherForecastClient&gt;();<\/code><\/p>\n<p>This will use <code>HttpClientFactory<\/code> behind the scenes, and ensure instances are pooled where required.<\/p>\n<p>Now our <code>WeatherForecastController<\/code> is much cleaner:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using Microsoft.AspNetCore.Mvc;\r\n\r\nnamespace Client.Controllers;\r\n\r\n[ApiController]\r\n[Route(\"[controller]\")]\r\npublic class WeatherForecastController : ControllerBase\r\n{\r\n    private readonly WeatherForecastClient _client;\r\n    public WeatherForecastController(WeatherForecastClient client)\r\n    {\r\n        _client = client;\r\n    }\r\n\r\n    [HttpGet]\r\n    public async Task&lt;IActionResult&gt; Get()\r\n    {\r\n        var response = await _client.GetAsync();\r\n\r\n        return Content(response, \"application\/json\");\r\n    }\r\n}<\/pre>\n<p>All our <code>HttpClient<\/code> configuration is now external to our logic, which means our controller can focus on the inputs and outputs, and not the HTTP semantics.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we demonstrate how to secure a server with Basic Authentication and configure a client to pass the appropriate credentials. Hopefully, with the approach shown and the modern usage of HttpClient, you are well-equipped to build scalable and secure solutions for your use case.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to discuss how to use basic authentication with HttpClient. While the topic may seem straightforward, there are a few different ways to solve this problem. We&#8217;ll try and cover some of the main approaches, and hopefully, by the end, we will know which approach is best and why. Before [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62187,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[171],"tags":[79,73,1811,716,1949,854],"class_list":["post-95019","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-http","tag-asp-net-core","tag-authentication","tag-c","tag-httpclient","tag-httpclient-authentication","tag-httpclientfactory","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Use Basic Authentication With HttpClient? - Code Maze<\/title>\n<meta name=\"description\" content=\"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Use Basic Authentication With HttpClient? - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-09-08T06:17:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-09-08T07:54:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Use Basic Authentication With HttpClient?\",\"datePublished\":\"2023-09-08T06:17:32+00:00\",\"dateModified\":\"2023-09-08T07:54:16+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\"},\"wordCount\":1383,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"keywords\":[\"asp.net core\",\"authentication\",\"C#\",\"HttpClient\",\"HttpClient Authentication\",\"HttpClientFactory\"],\"articleSection\":[\"HTTP\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\",\"url\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\",\"name\":\"How to Use Basic Authentication With HttpClient? - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"datePublished\":\"2023-09-08T06:17:32+00:00\",\"dateModified\":\"2023-09-08T07:54:16+00:00\",\"description\":\"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"width\":1100,\"height\":620,\"caption\":\"ASP.NET Core\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Use Basic Authentication With HttpClient?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Use Basic Authentication With HttpClient? - Code Maze","description":"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/","og_locale":"en_US","og_type":"article","og_title":"How to Use Basic Authentication With HttpClient? - Code Maze","og_description":"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.","og_url":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/","og_site_name":"Code Maze","article_published_time":"2023-09-08T06:17:32+00:00","article_modified_time":"2023-09-08T07:54:16+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Use Basic Authentication With HttpClient?","datePublished":"2023-09-08T06:17:32+00:00","dateModified":"2023-09-08T07:54:16+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/"},"wordCount":1383,"commentCount":2,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","keywords":["asp.net core","authentication","C#","HttpClient","HttpClient Authentication","HttpClientFactory"],"articleSection":["HTTP"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/","url":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/","name":"How to Use Basic Authentication With HttpClient? - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","datePublished":"2023-09-08T06:17:32+00:00","dateModified":"2023-09-08T07:54:16+00:00","description":"Here we look at basic authentication in ASP.NET Core, including the correct usage of HttpClient when sending the request.","breadcrumb":{"@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","width":1100,"height":620,"caption":"ASP.NET Core"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/aspnetcore-basic-authentication-with-httpclient\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Use Basic Authentication With HttpClient?"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/95019","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=95019"}],"version-history":[{"count":9,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/95019\/revisions"}],"predecessor-version":[{"id":95068,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/95019\/revisions\/95068"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62187"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=95019"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=95019"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=95019"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}