<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankit Rana on Medium]]></title>
        <description><![CDATA[Stories by Ankit Rana on Medium]]></description>
        <link>https://medium.com/@codeatom?source=rss-bac34b0cd163------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hiDmWy8fF_EfWL-jxQ54VA.png</url>
            <title>Stories by Ankit Rana on Medium</title>
            <link>https://medium.com/@codeatom?source=rss-bac34b0cd163------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:43:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codeatom/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Diffie-Hellman Key Exchange: A Secure Handshake in the Digital World]]></title>
            <link>https://medium.com/@codeatom/diffie-hellman-key-exchange-a-secure-handshake-in-the-digital-world-7774193927e4?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/7774193927e4</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[key-exchange]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 12:42:12 GMT</pubDate>
            <atom:updated>2025-07-13T13:10:05.818Z</atom:updated>
            <content:encoded><![CDATA[<p>The Diffie-Hellman (DH) key exchange is a foundational mathematical method that enables two parties to securely establish a shared secret key over an insecure public channel, even if they have no prior knowledge of each other. This secret key is crucial for subsequent secure communication using symmetric-key encryption. The protocol’s security relies on the concept of a one-way function, making it easy to compute in one direction but extremely difficult to reverse.</p><h3>The Lock and Key Analogy</h3><p>To understand how Diffie-Hellman works, consider an analogy involving padlocks and keys:</p><ol><li><strong>Alice’s Action:</strong> Alice places a secret message or item inside a box and locks it with a padlock that only she has the key for.</li><li><strong>Alice to Bob:</strong> She sends this double-locked box to Bob over the insecure channel.</li><li><strong>Bob’s Action:</strong> Bob receives the box and adds his own padlock to it, which only he has the key for.</li><li><strong>Bob to Alice:</strong> Bob sends the box back to Alice.</li><li><strong>Alice Unlocks:</strong> Alice receives the box and removes her padlock using her key.</li><li><strong>Alice to Bob (Again):</strong> Alice sends the box back to Bob.</li><li><strong>Bob Unlocks:</strong> Bob removes his padlock using his key, opening the box and gaining access to the secret message.</li></ol><p>Both Alice and Bob have successfully exchanged the secret without sending their keys over the insecure channel. An eavesdropper observing the process would only see the box being exchanged with different locks on it, but would not be able to open the box without both keys.</p><h3>The Mathematical Foundation and Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*t2wMWbb4pBu-8AHQ.png" /></figure><p>In the real-world Diffie-Hellman exchange, the process is implemented using large numbers and modular exponentiation. The security relies on the difficulty of solving the discrete logarithm problem.</p><p>Here is a simple example computation of the Diffie-Hellman key exchange:</p><p><strong>Publicly Agreed Values:</strong></p><ul><li>Modulus p = 23</li><li>Base g = 5</li></ul><p><strong>The Exchange:</strong></p><p><strong>Alice’s Secret and Public Key:</strong></p><ul><li>Alice chooses a secret integer a = 4.</li><li>She computes her public value A = 5^4 mod 23 = 4.</li><li>Alice sends A = 4 to Bob.</li></ul><p><strong>Bob’s Secret and Public Key:</strong></p><ul><li>Bob chooses a secret integer b = 3.</li><li>He computes his public value B = 5^3 mod 23 = 10.</li><li>Bob sends B = 10 to Alice.</li></ul><p><strong>Shared Secret Calculation:</strong></p><p><strong>Alice’s Calculation:</strong> Alice computes the shared secret s using Bob’s public value B and her secret a:</p><p>s = B^a mod p = 10^4 mod 23 = 18</p><p><strong>Bob’s Calculation:</strong> Bob computes the shared secret s using Alice’s public value A and his secret b:</p><p>s = A^b mod p = 4^3 mod 23 = 18</p><p>Both Alice and Bob arrive at the same shared secret, 18. This shared secret can now be used for secure communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7774193927e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Go Test Execution Summary Reports in GitHub Actions]]></title>
            <link>https://medium.com/@codeatom/integrating-go-test-execution-summary-reports-in-github-actions-35225d6c02b0?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/35225d6c02b0</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 06:01:01 GMT</pubDate>
            <atom:updated>2025-06-21T07:10:13.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phlYJ6PYvtJ7pxQVddmCeg.png" /></figure><p>GitHub Actions is a powerful Continuous Integration/Continuous Deployment (CI/CD) tool that enables developers to automate workflows directly within their repositories. When working with Go projects, generating and publishing test execution summary reports can provide valuable insights into test results, simplifying debugging and tracking. This article outlines how to integrate Go test execution summary reports into your GitHub Actions workflow using only the go-ctrf-json-reporter.</p><h3>Prerequisites</h3><p>Before you begin, ensure that you have the following:</p><ol><li>Your repository contains Go tests.</li><li>You have a GitHub Actions workflow file set up.</li><li>The essential tool go-ctrf-json-reporter is installed in your workflow.</li></ol><h3>Why CTRF?</h3><p>The <a href="https://ctrf.io/">Common Test Result Format</a> (CTRF) standardizes test result reporting, providing significant benefits for software testing teams and organizations. Its advantages include a consistent structure for reports, improved communication among stakeholders, and enhanced traceability by linking reports to specific test cases or defects. Additionally, CTRF supports integration with various testing tools, enabling automation in CI/CD pipelines, and facilitates compliance with regulatory standards. The format also allows for easier long-term analysis of test results and accommodates multiple testing types, ultimately leading to improved software quality and more effective testing.</p><h3>Setting Up GitHub Action for Go Tests with CTRF JSON Reporter</h3><p>To define a GitHub Action for running Go tests with the go-ctrf-json-reporter, you can create a workflow file (e.g., .github/workflows/execute-tests.yml) in your repository. Below is an example of how to set up the workflow:</p><pre>name: Go Test with CTRF Reporter<br>on:<br>  push:<br>    branches:<br>      - main<br>  workflow_dispatch:<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br>      - name: Set up Go<br>        uses: actions/setup-go@v2<br>        with:<br>          go-version: &#39;1.16&#39;# Specify the Go version you want to use<br>      - name: Install Dependencies<br>        run: go mod tidy<br>      - name: Execute tests<br>        run: |<br>          cd tests<br>          go test -json -p=4 -timeout 3600s 2&gt;&amp;1 | tee ./gotest.json || true<br>      - name: Generate test reports<br>        if: always()<br>        run: |<br>          go-ctrf-json-reporter -output ctrf-report.json &lt; gotest.json<br>      - name: Publish Test Summary Results<br>        if: always()<br>        run: npx github-actions-ctrf test_output/ctrf-report.json<br>      - name: Upload Test Results<br>        if: always()<br>        uses: actions/upload-artifact@v2<br>        with:<br>          name: test-results<br>          path: ./gotest.json</pre><h3>Explanation of the Workflow Steps:</h3><ol><li><strong>Triggering Events</strong>: The workflow is triggered on push events to the main branch or can be initiated manually.</li><li><strong>Checkout Code</strong>: The actions/checkout step checks out your repository code.</li><li><strong>Set up Go</strong>: The actions/setup-go step sets up the specified version of Go.</li><li><strong>Install Dependencies</strong>: This step runs go mod tidy to ensure all dependencies are installed.</li><li><strong>Execute Tests</strong>: Go tests are executed with the json flag, and the output is saved to gotest.json.</li><li><strong>Generate Test Reports</strong>: The go-ctrf-json-reporter tool processes the JSON output and generates a CTRF-compliant report.</li><li><strong>Publish Test Summary Results</strong>: The generated CTRF report is published using github-actions-ctrf.</li><li><strong>Upload Test Results</strong>: Finally, the test results are uploaded as artifacts for future reference.</li></ol><h3>Conclusion</h3><p>Integrating Go test execution summary reports into your GitHub Actions workflow using only go-ctrf-json-reporter can streamline your CI/CD pipeline and enhance the visibility of test results. The provided workflow illustrates how to execute tests, generate reports, and publish them effectively. Feel free to adapt this workflow to meet your project&#39;s specific needs and leverage automated reporting in your development process.d reporting in your development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35225d6c02b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforce Git Branch Naming Convention Using Husky.NET]]></title>
            <link>https://medium.com/@codeatom/enforce-git-branch-naming-convention-using-husky-net-9ef9afb87ef1?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ef9afb87ef1</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[shiftleft]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 06:55:14 GMT</pubDate>
            <atom:updated>2024-06-02T06:55:14.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ganW8t40fLMwChL4" /></figure><p>This is a continuing series of Husky.NET integrations with the DotNet project. In this post, we’ll look at how to use githooks to implement a branch name convention validation check for developers.</p><h3>Add Pre-Commit Hooks</h3><p>To set up Husky.NET with a dotnet project, please follow the instructions in this <a href="https://medium.com/@codeatom/integrate-githooks-using-husky-net-51122fdddbf5">link</a>. Next, you’ll need to establish a branch naming convention using Husky.NET. To do this, create a pre-commit hook script in the .husky directory that was generated by Husky.NET.</p><pre>dotnet husky add pre-commit &quot;branch naming convention&quot;</pre><h3>Prepare Branch Naming Convention Script</h3><p>Now, we will create a PowerShell script to enforce branch naming conventions. In this instance, we will utilize PowerShell to guarantee adherence to branch naming conventions. A PowerShell script for validation needs to be created and can be stored anywhere in your repository. It is recommended to save this script under the .husky folder.</p><pre>$branchName = git rev-parse --abbrev-ref HEAD<br>$pattern = &#39;^(topic)\/((\d+)(\.\d+)?(\.\d+))\/(\d+)\-(\w.*)$|Release_\d.*&#39;<br>if ($branchName -notmatch $pattern) {<br>    Write-Output &quot;Error: The branch name does not conform to the required naming convention. Please use the format &#39;topic/&lt;version&gt;/&lt;azure-task-id&gt;-&lt;description&gt;&#39; or &#39;Release_&lt;version&gt;&#39;.&quot; -ErrorAction Stop<br>    Exit -1;<br>}</pre><h3>Setting Up Branch Naming Validation in Husky.NET Task Runner</h3><p>Let’s proceed by adding the PowerShell script to the Husky.NET taskrunner. To begin, we should navigate to the .husky folder within our repository. Inside this folder, locate the task-runner.json file. Within this file, we will configure our PowerShell script as a task that can be executed in pre-commit Git hooks.</p><pre>{<br>   &quot;tasks&quot;: [<br>      {<br>         &quot;name&quot;: &quot;Branch Naming Convention&quot;,<br>         &quot;command&quot;: &quot;pwsh&quot;,<br>         &quot;args&quot;: [&quot;.husky/pre-commit-branch-naming-convention.ps1&quot; ]<br>      },<br>   ]<br>}</pre><h3>Configure Pre-Commit Hooks</h3><p>To configure the pre-commit hook, access the file in the .husky folder with name “pre-commit”. Then, include a command to trigger the branch naming convention task execution.</p><pre>#!/bin/sh<br>. &quot;$(dirname &quot;$0&quot;)/_/husky.sh&quot;<br>dotnet husky run --name &quot;Branch Naming Convention&quot;<br>/// other tasks.</pre><p>Now, every time you try to commit, Husky.NET will check if your branch name adheres to the naming convention. If it doesn’t, the commit will be aborted, and you’ll see an error message.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ef9afb87ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate GitHooks using Husky.NET]]></title>
            <link>https://medium.com/@codeatom/integrate-githooks-using-husky-net-51122fdddbf5?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/51122fdddbf5</guid>
            <category><![CDATA[husky]]></category>
            <category><![CDATA[shift-left-approach]]></category>
            <category><![CDATA[continous-testing]]></category>
            <category><![CDATA[git-hooks]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 18:58:04 GMT</pubDate>
            <atom:updated>2024-06-01T18:58:04.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*HLPxDX9R2eDzWBhc.png" /></figure><p>GitHooks are special scripts that Git executes before or after events such as: commit, push, and receive. These scripts are used to automate and customize Git’s internal behavior and to trigger customizable actions at key points in the development life cycle.</p><p>These hooks reside in the .git/hooks directory of every Git repository and are not copied to the clone repositories upon ‘git clone’. The hooks are all shell scripts, and you can write them in any scripting language supported by your environment.</p><h3>Why We Use GitHooks</h3><p>The primary reason for using GitHooks is to automate and streamline your development process. Here are some specific ways you can use GitHooks:</p><ol><li><strong>Enforce coding standards</strong>: You can use GitHooks to automatically check the code being committed and reject the commit if it doesn’t adhere to your coding standards.</li><li><strong>Automatic testing</strong>: GitHooks can automatically run unit tests on your code every time you commit changes, catching bugs early in the development process.</li><li><strong>Integration with issue tracking</strong>: You can link your GitHooks to your issue tracking system, so every commit is associated with a specific issue.</li><li><strong>Prevent unwanted actions</strong>: GitHooks can be used to prevent certain actions, like direct commits to main or master branches, ensuring that all changes go through the appropriate review and testing processes.</li></ol><p>Husky.NET is a .NET library that makes managing GitHooks in your .NET projects easier. By integrating GitHooks using Husky.NET, you can improve your project’s code quality and streamline your development process.</p><h3>Integration Steps</h3><ul><li><strong>Install </strong><a href="http://husky.net/"><strong>Husky.NET</strong></a>: Open a command prompt or terminal in your project’s root directory.</li></ul><pre>cd &lt;Your project root directory&gt;<br>dotnet new tool-manifest<br>dotnet tool install Husky</pre><ul><li><strong>Attach Husky to your project</strong></li></ul><p>To attach Husky to your project, you can use the following command:</p><pre>dotnet husky attach &lt;path-to-project-file&gt;</pre><p>This will add the required configuration to your project file.</p><pre>&lt;Target Name=&quot;husky&quot; BeforeTargets=&quot;Build&quot; Condition=&quot; &#39;$(Configuration)&#39; == &#39;Debug&#39; &quot;&gt;<br>  &lt;Exec Command=&quot;dotnet tool restore&quot; StandardOutputImportance=&quot;Low&quot; StandardErrorImportance=&quot;High&quot; /&gt;<br>  &lt;Exec Command=&quot;dotnet husky install&quot; StandardOutputImportance=&quot;Low&quot; StandardErrorImportance=&quot;High&quot; WorkingDirectory=&quot;../../&quot; /&gt;<br>  &lt;!--Update this to the relative path to your project root dir --&gt;<br>&lt;/Target&gt;</pre><h3>Integrate GitHook with Visual Studio</h3><ul><li>Install Git. <a href="https://git-scm.com/downloads">Git — Downloads</a></li><li>Add Git bin location to Window Path Variable(automatically done via installer).</li><li>Open Visual Studio, Go Tools menu → Options → Projects and Solutions → Web Package Management</li><li>Remove the current GIT Path from the external tools location.</li><li>Add the Git Path location.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yW2szlAZzcAhU37T.png" /></figure><ul><li>Restart Visual Studio.</li><li>Now GitHooks Integrate with Visual Studio.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51122fdddbf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SharedAPIKey Authentication in ASP.NET Core WebAPI]]></title>
            <link>https://medium.com/@codeatom/sharedapikey-authentication-in-asp-net-core-webapi-0a95a9ef38d2?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a95a9ef38d2</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sat, 18 May 2024 17:29:21 GMT</pubDate>
            <atom:updated>2024-05-18T17:41:39.525Z</atom:updated>
            <content:encoded><![CDATA[<p>API Key authentication represents the initial stage, or Level-0, within the API Security Maturity Model. In this phase, the focus is on basic security measures, primarily revolving around the use of API keys for authentication purposes. These keys are unique identifiers that grant access to the API and serve as a simple yet crucial first line of defence in API security.</p><p>Implementing SharedAPIKey authentication in <a href="http://asp.net/">ASP.NET</a> Core WebAPI involves creating a custom authentication scheme that checks for a valid API key on incoming requests. This key is typically passed in the request header and is validated against a stored key on the server but we can pass API key in query string also. If the key is valid, the request is allowed to proceed; if not, it is rejected.</p><ul><li>Define the Request API Key Provider to extract the API key from the request. You can define multiple providers to extract the API key from various sources such as headers, query strings, etc.</li></ul><pre>  public class ProviderApiKeyResult<br>    {<br>        public string ApiKey { get; set; }<br><br>        public ProviderApiKeyResult(string apiKey)<br>        {<br>            ApiKey = apiKey;<br>        }<br>    }<br><br>    public interface IRequestApiKeyProvider<br>    {<br>        Task&lt;ProviderApiKeyResult?&gt; DetermineProviderApiKeyResult(HttpContext httpContext);<br>    }<br>    <br>    public class RequestHeaderApiKeyProvider : IRequestApiKeyProvider<br>    {<br>        public string HeaderKey { get; set; } = &quot;X-API-KEY&quot;;<br><br>        public async Task&lt;ProviderApiKeyResult?&gt; DetermineProviderApiKeyResult(HttpContext httpContext)<br>        {<br>            if (!httpContext.Request.Headers.ContainsKey(HeaderKey))<br>            {<br>                return default;<br>            }<br>            var apiKey = httpContext.Request.Headers[HeaderKey];<br>            return new ProviderApiKeyResult(apiKey);<br>        }<br>    }</pre><ul><li>Create Shared API Key Authentication Options. In these options, you can configure your shared API key and Request API Key Providers.</li></ul><pre>public class SharedApiKeyAuthenticationOptions : AuthenticationSchemeOptions<br>{<br>    public string? SharedApiKey { get; set; }<br><br>    public ICollection&lt;IRequestApiKeyProvider&gt; RequestApiKeyProviders { get; set; } <br><br>    public SharedApiKeyAuthenticationOptions()<br>    {<br>       RequestApiKeyProviders = new HashSet&lt;IRequestApiKeyProvider&gt;();<br>       RequestApiKeyProviders.Add(new RequestHeaderApiKeyProvider());<br>    }<br>}</pre><ul><li>Create a custom authentication handler.</li></ul><pre> public class SharedApiKeyAuthenticationHandler : AuthenticationHandler&lt;SharedApiKeyAuthenticationOptions&gt;<br> {<br>     public SharedApiKeyAuthenticationHandler(<br>         IOptionsMonitor&lt;SharedApiKeyAuthenticationOptions&gt; options,<br>         ILoggerFactory logger,<br>         UrlEncoder encoder) : base(options, logger, encoder)<br>     {<br>     }<br><br>     protected override async Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()<br>     {<br>         ProviderApiKeyResult? providerApiKeyResult = null;<br>         if (Options.RequestApiKeyProviders != null)<br>         {<br>             foreach (var provider in Options.RequestApiKeyProviders)<br>             {<br>                 providerApiKeyResult = await provider.DetermineProviderApiKeyResult(Context);<br>                 if (providerApiKeyResult != null)<br>                 {<br>                     break;<br>                 }<br>             }<br>         }<br><br>         if (providerApiKeyResult == null)<br>         {<br>             return AuthenticateResult.NoResult();<br>         }<br><br>         if (providerApiKeyResult.ApiKey != Options.SharedApiKey)<br>         {<br>             return AuthenticateResult.Fail(&quot;API Key does not match&quot;);<br>         }<br>         var claimIdentity = new ClaimsIdentity(&quot;SharedAPIKey&quot;);<br>         claimIdentity.AddClaim(new Claim(&quot;Key&quot;, providerApiKeyResult.ApiKey));<br>         var claimPrincipal = new ClaimsPrincipal(claimIdentity);<br>         return AuthenticateResult.Success(new AuthenticationTicket(claimPrincipal, Scheme.Name));<br>     }<br> }</pre><ul><li>Configure new authentication scheme with custom authentication handler.</li></ul><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddAuthentication(&quot;ApiKey&quot;)<br>        AddScheme&lt;SharedApiKeyAuthenticationOptions, SharedApiKeyAuthenticationHandler&gt;(&quot;ApiKey&quot;, option =&gt; option.SharedApiKey = &quot;Test&quot;);<br>    // ... other services<br>}<br><br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    app.UseAuthentication();<br>    // ... other middleware<br>}</pre><ul><li>Configure controllers to use shared api key authentication scheme.</li></ul><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>[Authorize(AuthenticationSchemes = &quot;ApiKey&quot;)]<br>public class ValuesController : ControllerBase<br>{<br>    // ... your actions<br>}</pre><h3>Considerations for using shared API key authentication</h3><ol><li><strong>Never Expose API Keys in Public Repositories</strong>: Avoid hardcoding API keys in your codebase, especially if the code is stored in public repositories. This is one of the most common mistakes that can lead to key exposure.</li><li><strong>Use Environment Variables</strong>: Store your API keys in environment variables or configuration files that are not included in your version control system. Ensure that these files are listed in your .gitignore to prevent accidental exposure.</li><li><strong>Implement Key Rotation</strong>: Regularly rotate your API keys to minimize the risk of an old key being exploited. Update the keys in your application to match the new keys.</li><li><strong>Restrict Key Permissions</strong>: Limit what each API key can do by setting permissions. For instance, if a key only needs to read data, it shouldn’t have write permissions.</li><li><strong>Secure Key Storage</strong>: Use a secure storage solution for your API keys, such as a secrets management tool, hardware security module (HSM), or encrypted environment variables.</li><li><strong>Access Control</strong>: Ensure that only authorized personnel have access to API keys. Implement proper access controls and audit who has access to the keys.</li><li><strong>Monitor Usage</strong>: Keep track of how and when your API keys are used. This can help you detect unusual patterns that may indicate a security issue.</li><li><strong>Use HTTPS</strong>: Always use HTTPS to encrypt the transmission of your API keys over the network.</li><li><strong>Consider Using Tokens</strong>: For additional security, consider using tokens, which can be generated and validated dynamically, instead of static API keys.</li></ol><p>Source Code: <a href="https://gist.github.com/code-atom/2bebe459c756f15a519c3136b5be1a89">https://gist.github.com/code-atom/2bebe459c756f15a519c3136b5be1a89</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a95a9ef38d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix IIS Server Version Disclosure in ASP.NET CORE]]></title>
            <link>https://medium.com/@codeatom/fix-iis-server-version-disclosure-in-asp-net-core-8c09e991464b?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c09e991464b</guid>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sat, 11 May 2024 16:52:12 GMT</pubDate>
            <atom:updated>2024-05-11T17:24:03.525Z</atom:updated>
            <content:encoded><![CDATA[<p>The server header identifies the server software that processed the request and created the response. However, this header can reveal too much information, making the server vulnerable to attacks. Those with malicious intent can use this information to find weaknesses. If you’re using IIS with an <a href="http://asp.net/">ASP.NET</a> Core application, you’ll notice that IIS inserts a Server header into your HTTP headers, advertising the server platform.</p><p>One might assume you can just use Response.Headers.Remove(&quot;Server&quot;) to solve the issue. However, this approach doesn&#39;t work with the IIS Server header. Unlike other headers, it is not produced by the <a href="http://asp.net/">ASP.NET</a> Core framework, but by the IIS&#39;s internal pipeline, and IIS injects it late in the Response processing.</p><h3>Options 1: Removing the IIS Server Header — in web.config</h3><p>For this reason the reliable and most effective way to remove the Server header is <strong>to do it as part of the IIS processing configuration</strong>, in this case by using web.config and setting one of the requestFiltering options:</p><pre>&lt;system.webServer&gt;<br> &lt;security&gt;<br>    &lt;requestFiltering removeServerHeader=&quot;true&quot; /&gt;<br> &lt;/security&gt;<br>&lt;/system.webServer&gt;</pre><blockquote><em>This feature only works in IIS 10 which was introduced with Windows 10 and Windows Server 2016.</em></blockquote><p>This works great and it requires no other changes in your application. You’ll just have to ensure that you publish your custom web.config that includes the above &lt;security&gt; section with your application.</p><h3>Options 2: Overwrite the Server Header (Misdirection)</h3><p>If you’re comfortable with leaving a server header but want to misdirect by displaying a version of Apache or nginx instead of IIS, you can overwrite the server header with a new value.</p><p>So for example using the middleware I described in the previous post you can do:</p><pre>app.Use(async(context, next) =&gt;<br>{<br>    context.Response.Headers.Append(&quot;Server&quot;, &quot;nginx&quot;);<br>    await next();<br>});</pre><p>This produces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jChW3PKBUP00vdVy.png" /></figure><p>Apparently IIS won’t inject its own Server header, <strong>if your application already has set it</strong>. This means you can use your own header and add some misdirection for potential attacks against your server.</p><h3>What doesn’t work</h3><p><strong>Removing header via code in Middleware</strong></p><p>While you can modify headers with Response.Headers or generic middleware, the Server header, added late in the IIS request pipeline by IIS itself, can&#39;t be removed through <a href="http://asp.net/">ASP.NET</a> code to my knowledge.</p><p><strong>Kestrel Hosting Configuration Options</strong></p><p>Several older Posts and StackOverflow posts point at using Kestrel configuration options to remove the Server header via the Builder configuration. While that works for Kestrel&#39;s Server header, it has no effect on when hosted in IIS.</p><p><strong>Using the web.config</strong><strong>&lt;customHeaders&gt;Section</strong></p><p>Like the other approaches mentioned above you can’t use the IIS &lt;customHeaders&gt; configuration section to &lt;remove value=&quot;server&quot;&gt; either.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c09e991464b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shift Left in Agile/DevOps Development]]></title>
            <link>https://medium.com/@codeatom/shift-left-in-agile-devops-development-34c379777fc0?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c379777fc0</guid>
            <category><![CDATA[shiftleft]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 07:50:59 GMT</pubDate>
            <atom:updated>2024-03-12T09:05:10.413Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>As the demand to release quality software products in a short amount of time continues to accelerate, Agile and DevOps teams have to adopt new approaches to avoid falling behind. Continuous testing and shift left testing are two breakthrough solutions for them in the modern era of software delivery.</em></blockquote><blockquote><strong>Dev</strong>: Reposition the testing phase closer to the build delivery process.</blockquote><blockquote><strong>Tester</strong>: Performing testing in earlier development cycle to reduce bugs.</blockquote><h3>Shift Left</h3><p>Traditional software development model is based on requirement engineering takes place on the left side of the project planning while delivery and testing requirements are on the right side. The model is not very flexible with changing client’s expectations and requirements and leads to negative outcomes for the business such as increased costs, increased time to market, and unexpected errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MkV3d867ust-_4mX.png" /></figure><p>Shift Left Testing literally pushes testing to the “left,” i.e., to earlier stages in the pipeline. The Shift Left approach intends to identify and resolve bugs as early as possible in the development process. This improves software quality and reduces time spent in resolving issues (which usually magnifies as development progress) later in the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*gmIySJ5eFae5s23R.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*2ekOs6LN_f6_gB9B.png" /></figure><p>Shift Left is core testing concept of the Agile DevOps methodology, which speed up application development by release small builds frequently as code changes.</p><p>Shift left is all about shifting testing of the software to an early phase in the SDLC. <strong>Test automation</strong> and <strong>DevOps infrastructure</strong> are important ingredients to achieve success in increasing efficiency and quality.</p><p>Shift Left places strong emphasis on conducting testing activities earlier in the development process . It is a proactive testing approach based on the idea that the earlier defects are identified and resolved, preventing them from propagating across the entire application, the lower the cost and effort required for fixing.</p><p>Key elements of Shift Left Testing:</p><ul><li>Early Testing (Bugs less expensive and easier to fix)</li><li>Collaborative Approach</li><li>Automation</li></ul><p>Shift Left support different type of models in software development. For more details on this model</p><h3>Agile Shift Left Model</h3><p><a href="https://en.wikipedia.org/wiki/Agile_software_development">Agile</a> and <a href="https://en.wikipedia.org/wiki/DevOps">DevOps</a> projects are characterized by multiple short-duration sprints, as opposed to a single or a small number of longer phases, such as in shift-left testing. These shorter periods may be adjusted if early sprints are dedicated to defining basic requirements and architecture or implementing test-first and <a href="https://en.wikipedia.org/wiki/Test-driven_development">test-driven development</a> (TDD). The concept of “shift-left” arises from the fact that the types of testing performed during the initial stages of these smaller sprints precede those conducted during later stages of the larger sprint(s) they replace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*wHBOFqYTyJzcJnJ4.png" /></figure><p>While Agile and DevOps share similar features, Agile testing typically <strong>focuses on developmental testing rather than operational testing</strong>, which takes place after the system is deployed.</p><h3>Why?</h3><h3>Cost Effective</h3><p>When testing is paused until the end of development, any bugs that do show up will usually be more difficult to fix. Their resolution needs the software to be reworked in its entirety since all the code has already been created. Consequences of such an approach would be:</p><p>When it comes to fixing bugs, the earlier, the cheaper. According to the <a href="https://www.nist.gov/">NIST</a>, <a href="https://www.vorto.co/blog/2020/2/27/reduce-cost-defects-service-now#:%5C~:text=The%20relative%20cost%20of%20fixing,in%20case%20of%20security%20defects">resolving defects in production can cost 30 times more and up to 60 times more in case of security defects</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*VUSLlnVMDjYxPWs6.png" /></figure><p>The Shift Left Testing approach implements a process that lets developers <a href="https://www.browserstack.com/guide/how-to-find-bugs-in-software">find bugs</a> early and often. Bugs identified when code is being written or reviewed by devs are the easiest to fix because these code units are small and infinitely more manageable. Once merged into the main development branch, the breadth of code widens, and so does the effort required to find anomalies within it.</p><h3>Increase Team Velocity and Quality</h3><p>Since bugs could occur at any iteration of software development, it makes sense to also incorporate testing along the way to catch them and prevent further problems as soon as possible. Combining continuous testing and shift left testing is a great strategy to improve software quality, meet users’ expectations, optimize the allocated resources, and minimize risks of bug-breaking apps from slipping into production.</p><h3>How?</h3><p>Shifting left requires two key practices — <strong>continuous testing</strong> and <strong>continuous deployment.</strong></p><ul><li><strong>Continuous testing</strong> is the process of executing automated tests as early as possible, along with service virtualization to mimic unavailable systems. Continuous testing establishes a constant feedback loop from the testing team to the developers. It ensures prompt bug identification and early bug detection. The entire software development process is therefore more optimized at every stage. Continuous testing relies quite heavily on automation.</li><li><strong>Continuous deployment</strong>, the deployment pipelines are completely automated, and they have triggered automatically for every change or at an interval.</li></ul><h3>Risks of Shift Left</h3><p>With the availability of powerful automation tools, there’s a temptation to apply all kinds of testing to every line of code. However, this approach is risky.</p><p>While testing side effects such as verifying if a record was saved in the database may seem appealing, it’s important to note that testing implementation details is considered an anti-pattern due to its high susceptibility to breakage. These tests often require frequent modifications whenever changes are made to the application. Similarly, UI tests fall into this category since they focus on implementation specifics.</p><p>Verification tests just care about the “what,” not the “how” or the “why.” Ideally, the user requirements have been designed to validate “why.” To answer “how”, we can rely on a more powerful automation in the form of an observability platform.</p><p><strong>Reference</strong></p><ul><li><a href="https://dzone.com/articles/shifting-left-in-software-engineering">Shifting Left in Software Engineering - DZone</a></li><li><a href="https://www.browserstack.com/guide/what-is-shift-left-testing">Shift Left Testing: Approach, Strategy &amp; Benefits | BrowserStack</a></li><li><a href="https://www.bmc.com/blogs/what-is-shift-left-shift-left-testing-explained/">Shift Left Testing: What, Why &amp; How To Shift Left</a></li><li><a href="https://katalon.com/resources-center/blog/shift-left-testing-approach">What is Shift Left Testing? Shift Left Meaning in DevOps</a></li><li><a href="https://www.testim.io/blog/shift-left-testing-guide/">What Is Shift Left Testing? A Guide to Improving Your QA</a></li></ul><p><a href="https://www.dynatrace.com/news/blog/what-is-shift-left-and-what-is-shift-right/#:%5C~:text=Shift%20left%20is%20the%20practice,performance%20or%20other%20delivery%20processes.">https://www.dynatrace.com/news/blog/what-is-shift-left-and-what-is-shift-right/#:~:text=Shift%20left%20is%20the%20practice,performance%20or%20other%20delivery%20processes.</a></p><p><a href="https://www.ibm.com/topics/continuous-testing">https://www.ibm.com/topics/continuous-testing</a></p><ul><li><a href="https://www.ibm.com/topics/shift-left-testing">What is Shift-left Testing? | IBM</a></li><li><a href="https://insights.sei.cmu.edu/blog/four-types-of-shift-left-testing/">Four Types of Shift Left Testing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c379777fc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manual Validate Azure AD Graph API Access token]]></title>
            <link>https://medium.com/@codeatom/manual-validate-azure-ad-graph-api-access-token-35f1d451b210?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f1d451b210</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 15:56:26 GMT</pubDate>
            <atom:updated>2023-07-10T15:56:26.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ailDO2hh2ADvGo9Y" /></figure><p>Yesterday, one of my connections contacted me and asked for assistance with manually validating access tokens, stating that he was experiencing Signature validation errors. So I reasoned that there could be a problem with the signing keys used to validate the signature. However, after hours of investigation, we discovered that the access token we received from Azure Ad is produced for graph API and has a nonce value in the token header. As a result, our validation procedure fails.</p><p>Azure AD has two token-generating API versions. The regular token validation technique will work for version 1. However, before verifying the token for version 2, we must do some more work. You must extract the nonce from the JWT header, compute its SHA256, and then add it back to the JWT header.</p><pre>string[] parts = accessToken.Split(&#39;.&#39;);<br>string header = parts[0];<br>string payload = parts[1];<br>string signature = parts[2];<br>var tokenHandler = new JwtSecurityTokenHandler();<br>var jsonToken = tokenHandler.ReadJwtToken(accessToken);<br>if (jsonToken.Header.TryGetValue(&quot;nonce&quot;, out object nonceAsObject))<br>{<br>    string plainNonce = nonceAsObject.ToString();<br>    using (SHA256 sha256 = SHA256.Create())<br>    {<br>        byte[] hashedNonceAsBytes = sha256.ComputeHash(<br>            System.Text.Encoding.UTF8.GetBytes(plainNonce));<br>        string hashedNonce = Base64Url.Encode(hashedNonceAsBytes);<br>        jsonToken.Header.Remove(&quot;nonce&quot;);<br>        jsonToken.Header.Add(&quot;nonce&quot;, hashedNonce);<br>        header = tokenHandler.WriteToken(jsonToken).Split(&#39;.&#39;)[0];<br><br>        jsonToken = tokenHandler.ReadJwtToken($&quot;{header}.{payload}.{signature}&quot;);<br>    }<br>}</pre><p>Here is the full code with token generation and validation logic.</p><pre>var app = ConfidentialClientApplicationBuilder<br>.Create(&quot;XXXXXXXXXXXXXXXXX&quot;)<br>.WithClientSecret(&quot;XXXXXX&quot;)<br>.WithTenantId(&quot;XXXX&quot;)<br>.Build();<br><br>string[] scopes = new string[] { &quot;https://graph.microsoft.com/.default&quot; };<br>var authResult = await app.AcquireTokenForClient(scopes).WithForceRefresh(true).ExecuteAsync();<br>string accessToken = authResult.AccessToken;<br><br><br>var authorityEndpoint = &quot;https://login.microsoftonline.com/XXXX/v2.0/&quot;;<br>var openIdConfigurationEndpoint = $&quot;{authorityEndpoint}.well-known/openid-configuration&quot;;<br>IConfigurationManager&lt;OpenIdConnectConfiguration&gt; configurationManager = new ConfigurationManager&lt;OpenIdConnectConfiguration&gt;(openIdConfigurationEndpoint, new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever());<br>OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);<br>var keys = openIdConfig.SigningKeys.Where(x =&gt; x.GetType() == typeof(Microsoft.IdentityModel.Tokens.X509SecurityKey)).ToList();<br>TokenValidationParameters validationParameters = new TokenValidationParameters<br>{<br>  ValidateAudience = false,<br>  ValidateIssuer = false,<br>  IssuerSigningKeys = keys,<br>  ValidateLifetime = false,<br>  ValidateIssuerSigningKey = false,<br>  TokenReader = (string token, TokenValidationParameters validationParameters) =&gt;<br>  {<br>      string[] parts = token.Split(&#39;.&#39;);<br>      string header = parts[0];<br>      string payload = parts[1];<br>      string signature = parts[2];<br>      var tokenHandler = new JwtSecurityTokenHandler();<br>      var jsonToken = tokenHandler.ReadJwtToken(token);<br>      if (jsonToken.Header.TryGetValue(&quot;nonce&quot;, out object nonceAsObject))<br>      {<br>          string plainNonce = nonceAsObject.ToString();<br>          using (SHA256 sha256 = SHA256.Create())<br>          {<br>              byte[] hashedNonceAsBytes = sha256.ComputeHash(<br>                  System.Text.Encoding.UTF8.GetBytes(plainNonce));<br>              string hashedNonce = Base64Url.Encode(hashedNonceAsBytes);<br>              jsonToken.Header.Remove(&quot;nonce&quot;);<br>              jsonToken.Header.Add(&quot;nonce&quot;, hashedNonce);<br>              header = tokenHandler.WriteToken(jsonToken).Split(&#39;.&#39;)[0];<br><br>              jsonToken = tokenHandler.ReadJwtToken($&quot;{header}.{payload}.{signature}&quot;);<br>          }<br>      }<br>      return jsonToken;<br>  }<br>};<br>IdentityModelEventSource.ShowPII = true;<br>var handler = new JwtSecurityTokenHandler();<br>var user = handler.ValidateToken(accessToken, validationParameters, out var token);</pre><h3>Reference links</h3><ul><li><a href="https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609#issuecomment-405683736">https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609#issuecomment-405683736</a></li><li><a href="https://tonesandtones.github.io/azure-ad-and-the-unvalidatable-access-token/">https://tonesandtones.github.io/azure-ad-and-the-unvalidatable-access-token/</a></li><li><a href="https://stackoverflow.com/questions/56954716/cannot-validate-aad-access-token-idx10511-signature-validation-failed/71588115#71588115">https://stackoverflow.com/questions/56954716/cannot-validate-aad-access-token-idx10511-signature-validation-failed/71588115#71588115</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f1d451b210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strings and its memory allocation in .NET]]></title>
            <link>https://medium.com/@codeatom/strings-and-its-memory-allocation-in-net-cafe25965765?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/cafe25965765</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[netframework]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 17:32:00 GMT</pubDate>
            <atom:updated>2022-02-13T18:18:06.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strings and its memory allocation in .NET</h3><p>The string is the common data type and is almost used by every application. The string is a sequence of characters. Each character encoded in UTF-16 format, String data type has the following characteristics:</p><ul><li>It is a reference type</li></ul><p>The string is a reference type, which means the string is a type of object which is allocated in a special memory called Heap. It is immutable in nature which is why it’s treated the same as a value type.</p><ul><li>Immutable in nature</li></ul><p>The string is immutable in nature. Have you ever tried to change the string value without using reflection?. Actually, we change the string variable reference when we update the string</p><pre>string value = &quot;This is foo statement&quot;;<br>  value = value.replace(”foo”, “bar”);</pre><p>Above example, we update the value variable reference to point to a new string after replacing “foo” with “bar” in the value string. Due to this, strings are thread-safe.</p><ul><li>It overloads the == operator</li></ul><p>String use == operator, when comparing two string values. String.Equals method is used to compare the content of string variables. It only works if both operands are of string data type. If the object data type is used in that case reference equality is performed. Make sure when finding the equality of string always use string data type both side, operator are not applied polymorphically.</p><h3>When strings are allocated?</h3><p>When we create something inside “”, CLR will automatically generate string data type inside a memory. Although, you can create a string with their constructor. But in general, we use “”, read data from HTTP request or read content from the file, it will automatically generate a string object inside the memory. Due to immutable in nature, if you try to perform any operation, it will generate a new string object. But wait a minute, then what is string intern pool (aka string pool).</p><h3>String interning</h3><p>.NET has the concept of the intern pool, it is basically a set of strings, in which every time you refer to any string literal, it will always return the same reference of string.</p><p>Now the question is, how we can add the string inside a string intern pool?</p><p>String literals are automatically added to the intern pool by CLR. To manually, String.Intern method is used to add the strings inside a string intern pool. String.IsInterned method is used to check whether a string exists inside a string intern pool.</p><p>For example, the following snippet will only keep two strings around:</p><pre>var greetingText= &quot;Hello&quot;;<br><br>var stringList = new List&lt;string&gt;();<br>for (int i = 0; i &lt; 100; i++)<br>{<br>    stringList.Add(string.Intern(greetingText+ &quot; World&quot;));<br>}</pre><p>In the above example, “Hello” is literal, and automatically added in the intern pool and inside a for loop, we interned “Hello World” and for 100 calls, we always return the same string reference and add it into stringList. Optimized solution.</p><p>Now you can think why we can’t put every string inside memory or use the String.IsInterned method before creating any string, as it always returns the same reference, and CLR doesn&#39;t need to create string again and again.</p><p>In this case, we simply increase the CPU usage as first we need to check whether string exists then create string and in another case, we increase memory usage. so it depends on the use case and CLR is very optimized to clean up memory space. One more reason not to intern all strings automatically is that Interned strings no longer appear on the heap and are allocated on the intern pool instead. There is no garbage collection on that pool: this means those strings will stay in memory forever (well, for the lifetime of the AppDomain), even if they are no longer being referenced. So use with caution!</p><h3>Conclusion</h3><ul><li>If the application has a lot of frequently used strings and is not unique, in that case interning strings can improve the performance.</li><li>If the application has a unique and distinct string, in that case interning string affects the performance and memory usage.</li><li>If the application has short-lived strings, GC will handle the clean-up task.</li><li>When in doubt, measure. Use <a href="http://jetbrains.com/dotmemory">a memory profiler</a> to detect string duplicates and analyze where they come from and how they can be optimized. Do watch out: <a href="https://blogs.msdn.microsoft.com/tess/2009/02/27/net-memory-leak-reader-email-are-you-really-leaking-net-memory/">you may see strings as a potential memory issue but they most probably are not</a>.</li></ul><p><em>Originally published at </em><a href="https://codetalk.in/posts/2022/02/13/strings-and-its-memory-allocation-in-dot-net"><em>https://codetalk.in</em></a><em> on February 13, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cafe25965765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read request body multiple times in ASP.NET Core]]></title>
            <link>https://medium.com/@codeatom/read-request-body-multiple-times-in-asp-net-core-94b7a8a062eb?source=rss-bac34b0cd163------2</link>
            <guid isPermaLink="false">https://medium.com/p/94b7a8a062eb</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Ankit Rana]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 03:44:00 GMT</pubDate>
            <atom:updated>2022-01-04T04:02:03.644Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="http://asp.net/">ASP.NET</a> Core, the request can not be read once it is consumed. If you want to read the request body multiple times, you need to set</p><pre>context.Request.EnableBuffering()</pre><p>As you know, the request body stream is forward only, you can not read the content from the body once it gets read by middleware or handler. The above method introduced in <a href="http://asp.net/">ASP.NET</a> Core 2.1, provides multiple time seekable request body streams. This method copy incoming request body stream into<a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.filebufferingreadstream?view=aspnetcore-6.0.">FileBufferingReadStream</a>.</p><blockquote><strong><em>Note:</em></strong><em> </em><em>Request.EnableBuffering must be used before any operation is performed on the request body. As you know once the request body is read, it can not read again.</em></blockquote><p>FileBufferingReadStream wraps incoming request stream enable rewinding by buffering content as it is read. The content is buffered in memory up to a certain size and then spooled to a temp file on disk. The temp file will be deleted on request disposal.</p><p>Before <a href="http://asp.net/">ASP.NET</a> Core 2.1, Request.EnableRewind() get used to making seekable multiple times. Actually, Request.EnableBuffering() call Request.EnableRewind() method internally. But Request.EnableBuffering is in a public namespace rather than an internal one, it should be preferred over Request.EnableRewind().</p><p>Github: <a href="https://github.com/dotnet/aspnetcore/blob/ae1a6cbe225b99c0bf38b7e31bf60cb653b73a52/src/Http/Http/src/Internal/BufferingHelper.cs#L14">https://github.com/dotnet/aspnetcore/blob/ae1a6cbe225b99c0bf38b7e31bf60cb653b73a52/src/Http/Http/src/Internal/BufferingHelper.cs#L14</a></p><p>Then to read the body stream you could for example do this:</p><pre>string bodyContent = new StreamReader(Request.Body).ReadToEnd();</pre><blockquote><strong><em>Note</em></strong><em>: Do not wrap the stream reader instance in </em><em>using block, because it will dispose of the underline stream and code later in the request lifecycle won&#39;t be able to read the body.</em></blockquote><p>On the safer side, set the Request.Body.Position reset to 0. That way any code later in the request lifecycle will find the request body in the state just like it hasn&#39;t been read yet.</p><pre>Request.Body.Position = 0;</pre><p>Things to do for reading or seeking Request.Body multiple times:</p><ul><li>Use Request.EnableBuffering before any read operation on Request.Body stream.</li><li>Don’t dispose of the Stream via StreamReader instance.</li><li>Reset Request.Body.Position to 0.</li></ul><p><em>Originally published at </em><a href="https://codetalk.in/posts/2022/01/04/read-request-body-multiple-times-in-asp-dot-net-core"><em>https://codetalk.in</em></a><em> on January 4, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94b7a8a062eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>