<?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[Cheranga - Medium]]></title>
        <description><![CDATA[.NET, .NET Core, C#, ASP.NET Core, Architecture and Design - Medium]]></description>
        <link>https://medium.com/cheranga?source=rss----9d9327d82c31---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Cheranga - Medium</title>
            <link>https://medium.com/cheranga?source=rss----9d9327d82c31---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:14:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cheranga" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resilient HTTP Clients]]></title>
            <link>https://medium.com/cheranga/resilient-http-clients-b4374eaf6854?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/b4374eaf6854</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 02:49:34 GMT</pubDate>
            <atom:updated>2025-04-26T02:49:34.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScWE06D3a5AUORx1dMDTPw.png" /></figure><h3>📖 Context</h3><p>Resiliency is a key aspect of modern software development, especially when dealing with external services. This project demonstrates how to build resilient HTTP clients in a real world scenario.</p><p>We will explore the microsoft.extensions.http.resilience library, which provide mechanisms for handling resiliency and ensuring that our application can gracefully recover from failures.</p><p>Let’s list down what we will explore in here:</p><ul><li>A user requests bank accounts from a third party banking service</li><li>The third party service requires a token for authentication</li><li>Use a cache to store the token for a certain period of time</li><li>The third party can purge the active tokens at any time</li><li>Once the token is purged, the cached token needs to be invalidated because the token is no longer valid</li></ul><h3>💪 Designing Resiliency</h3><p>Designing resiliency does not mean just retrying, it means you need to design your resiliency to be specific and tailored to your need.</p><p>In here, the most important part of this integration is where the third party can invalidate the token at any time. The problem happens when we have a valid token which is cached. By default, the cache will not be invalidated until the expiration time, and until then we will keep getting an unauthorized response from the third party service.</p><p>So our application can’t just want until the token expires to get a new one, our application should detect this and then must take measures to rectify this as soon as possible.</p><p>So to solve this challenge, we need to design our resiliency in a way that we can detect when to invalidate the token, get a new one and use it in consecutive requests.</p><h3>✨ Technical Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjc4TGeES6LlDxDjRhbeZw.png" /></figure><h3>🍰 Components</h3><h3>📏 ResiliencePipeline</h3><p>This is a pipeline that will be used to define the resiliency logic. The benefit of completely separating the resiliency logic from other components is that you can reuse with any other component as you see fit.</p><pre>services.AddResiliencePipeline&lt;string, HttpResponseMessage&gt;(<br>    &quot;pipeline&quot;,<br>    (builder, context) =&gt;<br>    {<br>        var sp = context.ServiceProvider;<br>        builder.AddRetry(<br>            new HttpRetryStrategyOptions<br>            {<br>                MaxRetryAttempts = 1,<br>                BackoffType = DelayBackoffType.Linear,<br>                Delay = TimeSpan.FromSeconds(1),<br>                ShouldHandle = args =&gt;<br>                    args.Outcome.Result<br>                        is {<br>                            StatusCode: HttpStatusCode.Forbidden<br>                                or HttpStatusCode.Unauthorized<br>                        }<br>                        ? PredicateResult.True()<br>                        : PredicateResult.False(),<br>                OnRetry = async arguments =&gt;<br>                {<br>                    var cacheService = sp.GetRequiredService&lt;ITokenService&gt;();<br>                    await cacheService.GetTokenAsync(<br>                        arguments.Context.CancellationToken,<br>                        true<br>                    );<br>                },<br>            }<br>        );<br>    }<br>);</pre><p>Let’s break down the above code:</p><ul><li>It only retries once when the response is Forbidden or Unauthorized</li><li>OnRetry it will call the TokenService to get a new token</li><li>It uses a linear backoff strategy with a delay of 1 second</li><li>The resiliency pipeline/strategy is named as pipeline. By naming your pipelines, you can create as much as you want and reuse them in different components.</li><li>The pipeline is registered with its associated expected output type</li></ul><h3>🏦 BankAccountService</h3><p>This is a typed HTTP client that integrates with the third party banking service. Also, this is where we will use the resiliency logic.</p><pre>public interface IBankAccountService<br>{<br>    Task&lt;ListBankAccountsResponse&gt; ListBankAccountsAsync(CancellationToken token);<br>}<br><br>internal sealed class BankAccountService(<br>    HttpClient client,<br>    ResiliencePipelineProvider&lt;string&gt; pipelineProvider,<br>    ILogger&lt;BankAccountService&gt; logger<br>) : IBankAccountService<br>{<br>    public async Task&lt;ListBankAccountsResponse&gt; ListBankAccountsAsync(CancellationToken token)<br>    {<br>        var policy = pipelineProvider.GetPipeline&lt;HttpResponseMessage&gt;(&quot;pipeline&quot;);<br><br>        var httpResponse = await policy.ExecuteAsync(<br>            async ct =&gt; await client.GetAsync(&quot;/api/accounts&quot;, ct),<br>            token<br>        );<br><br>        var bankAccounts = await httpResponse.Content.ReadFromJsonAsync&lt;ListBankAccountsResponse&gt;(<br>            token<br>        );<br>        return bankAccounts ?? ListBankAccountsResponse.Empty;<br>    }<br>}</pre><p>The ResiliencePipelineProvider is injected into the BankAccountService client, and through that it can get the required pipeline by name.</p><p>Now we wrap the API call with the resiliency pipeline.</p><p>This will ensure that;</p><ul><li>If the response is Forbidden or Unauthorized, the resiliency strategy is applied as defined in the pipeline</li><li>The whole API call will be retried again once, which will use the new token</li></ul><p>As you can see the BankAccountService client is completely separated from the resiliency logic and contains only the business logic of calling the third party service.</p><h4>🤔 Why is resiliency applied in BankAccountService?</h4><p>Simply because it depends on “how and when” you want to apply the resiliency logic. According to our scenario explained above, we want to handle token invalidation from the third party service at any given time. This can be known only, when the third party service returns Forbidden or an Unauthorized response, and then only we could apply resiliency.</p><h3>🧾 TokenHandlerMiddleware</h3><p>This is a middleware that will be used to add the token to the request header. This middleware will be used in the BankAccountService client. The reason to do this is to separate the concerns of including a token in the header of each request sent through the BacnkAccountService.</p><h3>🧾 TokenService</h3><p>Another typed HTTP client which involves the token generation and caching it. It integrates with the Cache to store the token for a certain period of time. If the token is available, it will be used, otherwise a new token will be generated and stored in the cache.</p><h3>🏬 Cache</h3><p>In here we will use the microsoft.extensions.caching.memory library to cache the token. Depending on your needs, you can use other caching libraries like microsoft.extensions.caching.redis or microsoft.extensions.caching.sqlserver.</p><h3>🤯 Why not use HttpClients AddResiliencyHandler for this?</h3><p>With latest versions in microsoft.extensions.http.client you can add resiliency handlers to your HTTP client using AddResiliencyHandler.</p><p>You can use this in scenarios where you need to perform a retry with some logic, but the problem with it is as designed, it will reuse the same HTTPRequest in your consecutive requests. This is not going to work in our situation because we need the new token to be included in the header of the request.</p><p>Let’s explore the below code which adds resiliency to the HttpClient:</p><pre>services<br>    .AddHttpClient&lt;IBankAccountService, OtherBankAccountService&gt;()<br>    .ConfigureHttpClient(builder =&gt; builder.BaseAddress = new Uri(baseUrl))<br>    .AddHttpMessageHandler&lt;TokenHeaderMiddleware&gt;() // register the token middleware<br>    .AddResilienceHandler( // register the resiliency handler<br>        &quot;pipeline&quot;,<br>        (builder, context) =&gt;<br>        {<br>            var sp = context.ServiceProvider;<br>            builder.AddRetry(<br>                new HttpRetryStrategyOptions<br>                {<br>                    MaxRetryAttempts = 1,<br>                    BackoffType = DelayBackoffType.Linear,<br>                    Delay = TimeSpan.FromSeconds(1),<br>                    ShouldHandle = args =&gt; // retry only on unauthorized or forbidden<br>                        args.Outcome.Result is { StatusCode: HttpStatusCode.Unauthorized }<br>                            ? PredicateResult.True()<br>                            : PredicateResult.False(),<br>                    OnRetry = async arguments =&gt; // on retry, get a new token<br>                    {<br>                        var cacheService = sp.GetRequiredService&lt;ITokenService&gt;();<br>                        await cacheService.GetTokenAsync(arguments.Context.CancellationToken, true);<br>                    },<br>                }<br>            );<br>        }<br>    );</pre><p>Notice that the TokenHeaderMiddleware is registered to add the token to the request header, and the resiliency handler is registered after that. When using this approach, you must register your middlewares first before the resiliency handler. When a retry happens since HTTP requests are reused, this will NOT go through the same middlewares again. This is what stumps most engineers thinking that the middleware will be executed again.</p><p>We have a test case implemented which simulates the problem. In there, we assert whether a new token was included in the header, and the test fails because the same request is reused with the old token.</p><p>Please refer <a href="https://github.com/Cheranga/coding-delights/blob/8e901c47a6323803f1fb47f0c1bac873142106e1/articles/ResilientHttpClients/tests/ResilientHttpClients.Services.Tests/BankAccountServiceTests.cs#L59">Test2 </a>which illustrates this.</p><p>Now let’s explore how we can test this scenario.</p><h3>🧪 Testing</h3><p>Our main focus in this article is to test the resiliency, and the best way to test this is through integration tests.</p><p>Main nuget packages used for testing:</p><ul><li>WireMock.Net for mocking the third party service</li><li>BunsenBurner for writing beautifully organized tests</li><li>AutoBogus for generating realistic test data</li></ul><h3>⛑️ Handling different scenarios with WireMock.Net</h3><p>When using WireMock.Net, you can create stateful scenarios to test different cases. This is crucial for our testing because we need to return different responses to simulate the resiliency.</p><p>According to WireMock.Net documentation, you can do this like below.</p><pre>Server<br>    .Given(Request.Create().UsingGet().WithPath(&quot;/api/accounts&quot;))<br>    .InScenario(&quot;testing&quot;)<br>    .WhenStateIs(&quot;started&quot;)<br>    .WillSetStateTo(&quot;next&quot;)<br>    .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.Unauthorized));<br><br>Server<br>    .Given(Request.Create().UsingGet().WithPath(&quot;/api/accounts&quot;))<br>    .InScenario(&quot;testing&quot;)<br>    .WhenStateIs(&quot;next&quot;)<br>    .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK).WithBodyAsJson(expectedBankAccountsResponse));</pre><p>In my opinion, this is too much boilerplate code, just to achieve this. So in here I have implemented a custom response provider which can be easily hooked up to the WireMock.Net server.</p><pre>internal sealed class CustomResponseProvider : IResponseProvider<br>{<br>    private readonly Queue&lt;Func&lt;IResponseBuilder&gt;&gt; _responses;<br>    private readonly List&lt;IRequestMessage&gt; _capturedRequests = [];<br><br>    private CustomResponseProvider(Queue&lt;Func&lt;IResponseBuilder&gt;&gt; responses)<br>    {<br>        _responses = responses;<br>    }<br><br>    public static CustomResponseProvider New(params Func&lt;IResponseBuilder&gt;[] funcs)<br>    {<br>        return new CustomResponseProvider(new Queue&lt;Func&lt;IResponseBuilder&gt;&gt;(funcs));<br>    }<br><br>    public IReadOnlyList&lt;IRequestMessage&gt; CapturedRequests =&gt; _capturedRequests;<br><br>    public async Task&lt;(IResponseMessage Message, IMapping? Mapping)&gt; ProvideResponseAsync(<br>        IMapping mapping,<br>        IRequestMessage requestMessage,<br>        WireMockServerSettings settings<br>    )<br>    {<br>        if (_responses.TryDequeue(out var responseFunc))<br>        {<br>            _capturedRequests.Add(requestMessage);<br>            return await responseFunc().ProvideResponseAsync(mapping, requestMessage, settings);<br>        }<br><br>        throw new Exception(&quot;No response queued&quot;);<br>    }<br>}</pre><p>What it does basically is storing the responses you would like to return in a queue, and also keep a track of the requests that were sent to the server.</p><p>Below is how you use it.</p><pre>private CustomResponseProvider SetupBankAccountResponseProvider(ListBankAccountsResponse expectedBankAccountsResponse)<br>{<br>    var bankAccountResponseProvider = CustomResponseProvider.New(<br>        () =&gt; Response.Create().WithStatusCode(HttpStatusCode.Unauthorized),<br>        () =&gt; Response.Create().WithStatusCode(HttpStatusCode.OK).WithBodyAsJson(expectedBankAccountsResponse)<br>    );<br>    Server.Given(Request.Create().UsingGet().WithPath(&quot;/api/accounts&quot;)).RespondWith(bankAccountResponseProvider);<br><br>    return bankAccountResponseProvider;<br>}</pre><h3>👨‍⚕️ Testing resiliency with token generation, caching and invalidation</h3><p>This is the scenario we are testing.</p><ul><li>There’s a token in the cache</li><li>The API returns an Unauthorized response</li><li>Resiliency is applied</li><li>A new token is generated</li><li>The new token is cached</li><li>The new token is used in the next request</li><li>The API returns a successful response</li></ul><p>Refer the <a href="https://github.com/Cheranga/coding-delights/blob/main/articles/ResilientHttpClients/tests/ResilientHttpClients.Services.Tests/BankAccountServiceTests.cs">Test1</a> for the full test case.</p><h3>🫵 Important</h3><p>Most importantly, refer to the <a href="https://github.com/Cheranga/coding-delights/blob/main/articles/ResilientHttpClients/tests/ResilientHttpClients.Services.Tests/BankAccountServiceTests.cs">Test2</a>. This illustrates why this approach is wrong to be used in this scenario.</p><p>For the sake of passing the test, I have commented on the real assertion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5G1aJtziunRXUQX0" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4374eaf6854" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/resilient-http-clients-b4374eaf6854">Resilient HTTP Clients</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Husky with CSharpier]]></title>
            <link>https://medium.com/cheranga/using-husky-with-csharpier-53a81cf19a44?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/53a81cf19a44</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 22:19:43 GMT</pubDate>
            <atom:updated>2025-03-07T22:29:37.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0vcm4_dKk18TlHroZtlmQ.png" /></figure><h3>🎖️ Context</h3><p>This article is about using Husky to automate the enforcing of</p><p>✅ Code formatting before committing changes</p><p>✅Enforcing commit message pattern</p><h3>🙋 What is Husky.NET?</h3><p><a href="https://alirezanet.github.io/Husky.Net/guide/#features">Husky.Net</a> is a tool which can be used to run tasks integrated with git hooks. For the purpose of this article, we will use Husky to run tasks in the pre-commit and commit-msg hooks.</p><p>✅ In the pre-commit hook, we will run CSharpier to format the C# code before committing the changes.</p><p>✅ In the commit-msg hook, we will run a script to check if the commit message follows the conventional commit message format.</p><h3>🙋 What is CSharpier and why do we need it?</h3><p><a href="https://csharpier.com/docs/About">CSharpier</a> is an opinionated code formatter for C#. It is a tool that can be used to format the C# code in a consistent way.</p><p>Developers share different IDEs and editors, and each of them has its own code formatting rules. Also developers have their personal preferences as well.</p><p>But when working in a team, it is important to have a consistent code style in your code, and use it throughout your repositories.</p><h3>🤔 Why not StyleCop?</h3><p>Simply StyleCop does too many things in my opinion. After the more mature analyzers introduced by Microsoft and other open source community, I think we can finally separate code analyzers and code formatters.</p><p>Use code analysers for code quality and a formatting tool such as CSharpier for code formatting.</p><h3>⚒️ Installing CSharpier</h3><p>CSharpier is implemented as a dotnet tool.</p><ul><li>If you don&#39;t have any dotnet tools configured, create a tool manifest</li></ul><p>dotnet new tool-manifest</p><ul><li>Installing CSharpier as a tool</li></ul><p>dotnet tool install csharpier</p><ul><li>CSharpier is ready to use now</li></ul><p>Running the below command from your root directory will format, all the C# files.</p><p>dotnet csharpier .</p><ul><li>Configuring CSharpier for your preferences</li></ul><p>CSharpier can be configured using any of the below configuration files.</p><p>✅ .csharpierrc file in JSON or YAML</p><p>✅ .csharpierrc.json file or .csharpierrc.yaml file</p><p>✅ .editorconfig file</p><p>The preference will be given to the .csharpierrc file based on the location of the file being formatted.</p><p><strong><em>At this point, unless we run </em></strong><strong><em>CSharpier explicitly, we can commit unformatted code. Also nothing stops us using any text as a commit message when commiting.</em></strong></p><p><a href="https://csharpier.com/docs/Configuration">Read the docs for more details</a></p><h3>⚒️ Installing Husky.Net</h3><p>Husky.Net is also implemented as a dotnet tool.</p><ul><li>Installing Husky.Net as a dotnet tool</li></ul><p>dotnet tool install husky</p><ul><li>Integrate git hooks with Husky.Net</li></ul><p>dotnet husky install</p><ul><li>Adding a pre-commit hook</li></ul><p>dotnet husky add pre-commit -c &quot;echo &#39;Hi Husky!&#39;&quot;</p><ul><li>Adding a commit-msg hook</li></ul><p>dotnet husky add commit-msg -c &quot;echo &#39;Hi Husky!&#39;&quot;</p><p>After running these commands respective files are created with the hook name. In these files you can write the command/s to execute. There could be many tasks which you need to execute for a single hook.</p><p>So a better approach is to organize the tasks in the task-runner.json file.</p><h3>🧮 Configuring Husky.Net’s own task-runner.json</h3><pre>{<br>  &quot;$schema&quot;: &quot;https://alirezanet.github.io/Husky.Net/schema.json&quot;,<br>  &quot;tasks&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Run CSharpier&quot;,<br>      &quot;group&quot;: &quot;pre-commit&quot;,<br>      &quot;command&quot;: &quot;dotnet&quot;,<br>      &quot;args&quot;: [<br>        &quot;csharpier&quot;,<br>        &quot;.&quot;<br>      ]<br>    },<br>    {<br>      &quot;name&quot;: &quot;Conventional Commit Linter&quot;,<br>      &quot;command&quot;: &quot;bash&quot;,<br>      &quot;group&quot;: &quot;commit-msg&quot;,<br>      &quot;args&quot;: [<br>        &quot;.husky/commit-msg.sh&quot;,<br>        &quot;${args}&quot;<br>      ]<br>    }<br>  ]<br>}</pre><p>There are two tasks, Run CSharpier and Conventional Commit Linter. As you can see both these tasks belong to the groups pre-commit and commit-msg respectively.</p><ul><li>Configuring the pre-commit hook</li></ul><p>Edit the pre-commit file to run the tasks in the pre-commit group.</p><pre>#!/bin/sh<br>. &quot;$(dirname &quot;$0&quot;)/_/husky.sh&quot;<br><br>dotnet husky run --group pre-commit</pre><p>Edit the commit-msg file to run the tasks in the commit-msg group.</p><pre>#!/bin/sh<br>. &quot;$(dirname &quot;$0&quot;)/_/husky.sh&quot;<br><br>dotnet husky run --group commit-msg -a $1</pre><p>I am using a commit standard called <a href="https://www.conventionalcommits.org/en/v1.0.0/">conventional commits</a>.</p><p>In here I am using a bash script to be executed in the commit-msg hook</p><pre>#!/usr/bin/env bash<br><br>requiredPattern=&quot;^(build|[Cc]hore|ci|docs|feat|fix|perf|refactor|revert|style|test|Publish)(\([a-zA-Z]{3,}\-[0-9]<br>{1,7}\))?: .*&quot;<br><br>error_msg=&#39;<br>❌ Commit message does not follow the Conventional Commit standard!<br><br>Examples of valid commit messages are,<br>✅ feat(auth): add login functionality<br>✅ fix(user-profile): fix avatar upload issue<br>✅ docs: update API documentation<br>&#39;<br><br>commit_msg=$(cat $1)<br><br>echo &quot;Commiting changes with.....&quot; &gt;&amp;2<br>echo &quot;${commit_msg}&quot; &gt;&amp;2<br><br>if ! [[ $commit_msg =~ $requiredPattern ]];<br>then<br>echo &quot;${error_msg}&quot; &gt;&amp;2<br>echo &quot;Commit message input: &quot;<br>echo &quot;${commit_msg}&quot;<br>exit 1<br>fi</pre><h3>😎 Using C# code in your git hooks</h3><p>Best thing is you can write C# scripts and use them in your git hooks.</p><p>I have included the same script as in the <a href="https://alirezanet.github.io/Husky.Net/guide/csharp-script.html">documentation</a> as an example.</p><h3>💡What to do when you clone this repository for the first time?</h3><p>If you clone this repository for the first time, you don’t have the relevant tools installed, and you don’t have the git hooks associated with you.</p><p>So you MUST run the below commands to properly integrate the tools and the git hooks. <strong>You only need to do this once.</strong></p><pre>dotnet tool restore<br>dotnet husky install</pre><p>Let me know your thoughts and feedbacks in comments.</p><p><a href="https://github.com/Cheranga/coding-delights/tree/main/articles/HuskyCSharpier">You can find the code in GitHub</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a81cf19a44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/using-husky-with-csharpier-53a81cf19a44">Using Husky with CSharpier</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bunsen Burner — Set your tests on fire! ]]></title>
            <link>https://medium.com/cheranga/bunsen-burner-set-your-tests-on-fire-d9a71e73c954?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/d9a71e73c954</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sat, 11 May 2024 06:23:03 GMT</pubDate>
            <atom:updated>2024-05-11T06:35:23.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bunsen Burner — Set your tests on fire! 🔥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*7Xd47yekzx8Kn9wjcEJlqw.png" /><figcaption><a href="https://github.com/bmazzarol/Bunsen-Burner">https://github.com/bmazzarol/Bunsen-Burner</a></figcaption></figure><h3>Bunsen Burner 🔥</h3><p>A <a href="https://github.com/bmazzarol/Bunsen-Burner">testing library</a> which makes it easier to write well-structured test cases in both “Arrange, Act, Assert (AAA)”, and “Given, When, Then (BDD)” testing patterns.</p><p>Code for this article <a href="https://github.com/Cheranga/LetsDoIt/tree/main/src/ToDo.Api">can be found in here</a></p><h3>Context 🎯</h3><p>When it comes to testing .NET applications, there are many options, and opinions.</p><p>It’s always better to have a variety of options to choose from, and it really comes down to the team and the practices followed by that team.</p><p>But regardless of the chosen practice; writing better tests with structure and organization has always been important, and this is where <strong>Bunsen Burner</strong> comes in.</p><p>Bunsen Burner makes writing well-structured tests easier.</p><h3>Why Bunsen Burner? ❓</h3><p>✅ Can easily write tests in a more structured and organized manner</p><p>✅ If you can write basic C#, that’s it! Nothing new to learn</p><p>✅ Both “AAA”, and “BDD” styles are supported through in a fluent way</p><p>✅ Easily extendable using simple methods</p><p>✅ Having methods makes it DRY</p><p>✅ You could even pull these methods into a separate class, or library to reuse across projects</p><p>✅ Async first design so that you can write synchronous or asynchronous tests with ease (this is as per design in Bunsen Burner)</p><h3>Let’s write some fun math tests</h3><p>You can find these tests in the <a href="https://github.com/Cheranga/LetsDoIt/blob/main/tests/LetsDoIt.ToDoApi.BunsenBurner.Tests/ExampleTests.cs">ExampleTests.cs</a> file in the “LetsDoIt.ToDoApi.BunsenBurner.Tests” project.</p><h4>Adding Numbers</h4><p>Using Bunsen Burner,</p><pre>[Theory(DisplayName = &quot;Adding numbers&quot;)]<br>[InlineData(1, 1, 2)]<br>[InlineData(1, -1, 0)]<br>public static async Task TestAddWithBunsen(int a, int b, int expected) =&gt;<br>    await Arrange(() =&gt; (a,b))<br>        .Act(input =&gt; input.a + input.b)<br>        .Assert(result =&gt; result == expected);</pre><p>Without using Bunsen Burner,</p><pre>[Theory(DisplayName = &quot;Adding numbers&quot;)]<br>[InlineData(1, 1, 2)]<br>[InlineData(1, -1, 0)]<br>public static void TestAdd(int a, int b, int expected)<br>{<br>    // Arrange (the input data is provided)<br><br>    // Act<br>    var result = a + b;<br><br>    // Assert<br>    Assert.Equal(expected, result);<br>}</pre><p>✅ When using Bunsen Burner, the Arrange, Act, and the Assert sections are separated</p><p>✅ No need to add comments to separate the sections</p><p>✅ You can have predicate expressions in the Assert section. This is not possible without using Bunsen Burner</p><p>✅ The function chaining pattern, makes it easier to read, and understand the “flow” of the test</p><h4>Division by zero</h4><p>Using Bunsen Burner,</p><pre>[Fact(DisplayName = &quot;Division by zero&quot;)]<br>public static async Task DivisionByZeroBunsen() =&gt;<br>    // ReSharper disable once IntDivisionByZero<br>    await 1<br>        .ArrangeData()<br>        .Act(x =&gt; x / 0)<br>        .AssertFailsWith(exception =&gt;<br>        {<br>            Assert.IsType&lt;DivideByZeroException&gt;(exception);<br>        })<br>        .And(exception =&gt; exception.Message == &quot;Attempted to divide by zero.&quot;);</pre><p>Without using Bunsen Burner,</p><pre>[Fact(DisplayName = &quot;Division by zero&quot;)]<br>public static void DivisionByZero()<br>{<br>    // Arrange<br>    var denominator = 0;<br><br>    // Act and Assert<br>    var exception = Assert.Throws&lt;DivideByZeroException&gt;(() =&gt; 1 / denominator);<br>    Assert.Equal(&quot;Attempted to divide by zero.&quot;, exception.Message);<br>}</pre><p>✅ Regardless of the exception being thrown the Arrange, Act, and the Assert sections are separated and remain the same</p><p>✅ Extension methods such as “ArrangeData” are been provided, so an object can be lifted into an Arrange section</p><p>✅ By using the function chaining pattern, you can easily add more assertions to the test (this can be done for Arrange, and Act sections as well)</p><p>Well enough with the math tests, let’s move on to something more interesting! 🎉</p><h3>System Under Test <strong>🎉</strong></h3><p>It&#39;s a simple task management API, where you can perform,</p><p>✅ Adding a task</p><p>✅ Getting all tasks</p><p>✅ Getting a task by id</p><p>To keep things simple, we are using entity framework’s in-memory database for the data operations.</p><p>And to make things interesting we are adding distributed caching when getting all tasks, and an endpoint filter for validation when adding a task.</p><h4>Adding a Task</h4><p>We will include an endpoint filter to perform validation on the input request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*XlG56JC2o_rhOHjnl2jVyg.png" /></figure><h4>Geting All Tasks</h4><p>In here we’ll use an endpoint filter to cache the tasks retrieved from the database.</p><p>To implement distributed caching, we are using Microsoft.Extensions.Caching.Memory which is an in-memory implementation of IDistributedCache .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*hc3pS3_OY9c_oXJodZc2vQ.png" /></figure><h4>Searching Tasks by Id</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*T9TABPS3Ozo6xx3tHcTZXg.png" /></figure><h3>Testing Getting All Tasks</h3><p>We’ll use unit tests to test the internal operations, and an integration test approach to test the behaviour of this feature from an endpoint perspective.</p><p>For unit tests, let’s use the AAA pattern, and for integration tests the behavioural pattern.</p><h4>Unit tests for the GetAll.Operations</h4><p>Cache only if tasks are in the database,</p><pre>[Fact(DisplayName = &quot;Cache only if tasks are available in database&quot;)]<br>public static async Task CacheOnlyIfTasksAreAvailable()<br>{<br>    // Arrange<br>    var mockedCache = new Mock&lt;IDistributedCache&gt;();<br><br>    var mockedQueryHandler = new Mock&lt;IQueryHandler&lt;SearchAllQuery,<br>        List&lt;TodoDataModel&gt;&gt;&gt;();<br>    mockedQueryHandler<br>        .Setup(x =&gt; x.QueryAsync(It.IsAny&lt;SearchAllQuery&gt;(), It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync([]);<br><br>    // Act<br>    var response = await Operations.ExecuteAsync(mockedCache.Object, mockedQueryHandler.Object, Mock.Of&lt;ILogger&lt;Program&gt;&gt;());<br><br>    // Assert<br>    mockedCache.Verify(<br>        x =&gt;<br>            x.SetAsync(<br>                Constants.CacheKey,<br>                It.IsAny&lt;byte[]&gt;(),<br>                It.IsAny&lt;DistributedCacheEntryOptions&gt;(),<br>                It.IsAny&lt;CancellationToken&gt;()<br>            ),<br>        Times.Never()<br>    );<br><br>    response.Result.Should().BeOfType&lt;NoContent&gt;();<br>}</pre><p>As you can see above, we usually use “comments” to segregate the arranges, act, and the respective asserts.</p><p>This test could be a simple one to contrast against as this test does not contain complicated arrange sections or assertions.</p><p>But if you imagine a test case where you had to setup a few more things, and there were many assertions then using this approach could become messy.</p><p>Using Bunsen Burner for the same test,</p><pre>[Fact(DisplayName = &quot;Cache only if tasks are available in database&quot;)]<br>public static async Task CacheOnlyIfTasksAreAvailable() =&gt;<br>    await Arrange(() =&gt;<br>        {<br>            var mockedCache = new Mock&lt;IDistributedCache&gt;();<br><br>            var mockedQueryHandler = new Mock&lt;IQueryHandler&lt;SearchAllQuery, List&lt;TodoDataModel&gt;&gt;&gt;();<br>            mockedQueryHandler<br>                .Setup(x =&gt; x.QueryAsync(It.IsAny&lt;SearchAllQuery&gt;(), It.IsAny&lt;CancellationToken&gt;()))<br>                .ReturnsAsync([]);<br><br>            return (mockedCache, mockedQueryHandler);<br>        })<br>        .Act(async data =&gt;<br>            await Operations.ExecuteAsync(<br>                data.mockedCache.Object,<br>                data.mockedQueryHandler.Object,<br>                Mock.Of&lt;ILogger&lt;Program&gt;&gt;()<br>            )<br>        )<br>        .Assert(<br>            (data, _) =&gt;<br>            {<br>                data.mockedCache.Verify(<br>                    x =&gt;<br>                        x.SetAsync(<br>                            Constants.CacheKey,<br>                            It.IsAny&lt;byte[]&gt;(),<br>                            It.IsAny&lt;DistributedCacheEntryOptions&gt;(),<br>                            It.IsAny&lt;CancellationToken&gt;()<br>                        ),<br>                    Times.Never<br>                );<br>            }<br>        )<br>        .And(response =&gt; { response.Result.Should().BeOfType&lt;NoContent&gt;(); });</pre><p>There are some striking differences with this approach.</p><p>✅ The Arrange, Act, and the Assertions have been separated</p><p>✅ Multiple “arrange” sections, and “assert” sections can be written using a fluent approach</p><p>✅ Arranged data is passed to the Act section as a function parameter</p><p>✅ All the “Arranged” data, and the “Act/s” are passed to the “Assert” section for assertions</p><p><strong><em>Note: Please refer to the other tests for the “Operations” class with and without using Bunsen Burner.</em></strong></p><h3>Integration Tests of the GetAll Endpoint</h3><p>Here we are using Microsoft.AspNetCore.Mvc.Testing to set up integration tests using Test server, and we’ll be using the behavioural pattern.</p><p>Without using Bunsen Burner</p><pre>[Fact(DisplayName = &quot;Given tasks are cached, when get all endpoint is called, then must return tasks from the cache&quot;)]<br>public async Task GetAllTasksWhenCached()<br>{<br>    // Given<br>    var fixture = new Fixture();<br>    var mockedQueryHandler = GetMockedQueryHandler(<br>        [],<br>        fixture.CreateMany&lt;TodoDataModel&gt;(5).ToList(),<br>        fixture.CreateMany&lt;TodoDataModel&gt;(10).ToList()<br>    );<br>    var httpClient = factory<br>        .WithWebHostBuilder(builder =&gt;<br>        {<br>            builder.ConfigureTestServices(services =&gt;<br>            {<br>                services.AddSingleton(mockedQueryHandler.Object);<br>            });<br>        })<br>        .CreateClient();<br><br>    // When<br>    // Call the endpoint three times<br>    var httpResponse1 = await httpClient.GetAsync(&quot;/todos&quot;);<br>    var httpResponse2 = await httpClient.GetAsync(&quot;/todos&quot;);<br>    var httpResponse3 = await httpClient.GetAsync(&quot;/todos&quot;);<br><br>    // Then<br>    // The query handler must be called only two times, as the third response must be taken from the cache<br>    mockedQueryHandler.Verify(x =&gt; x.QueryAsync(It.IsAny&lt;SearchAllQuery&gt;(), It.IsAny&lt;CancellationToken&gt;()), Times.Exactly(2));<br>    // The first response must be 204 No Content<br>    // The second and third responses must be 200 OK<br>    httpResponse1.StatusCode.Should().Be(HttpStatusCode.NoContent);<br>    httpResponse2.StatusCode.Should().Be(HttpStatusCode.OK);<br>    httpResponse3.StatusCode.Should().Be(HttpStatusCode.OK);<br><br>    var todoListResponse = await GetToDoListResponse(httpResponse2);<br>    todoListResponse.Should().NotBeNull();<br>    todoListResponse!.Tasks.Should().NotBeNull().And.HaveCount(5);<br><br>    todoListResponse = await GetToDoListResponse(httpResponse3);<br>    todoListResponse.Should().NotBeNull();<br>    todoListResponse!.Tasks.Should().NotBeNull().And.HaveCount(5);<br>}</pre><p>As you could see, there’s lot going on in the setup and in the assertions, and this could easily detract from what we are trying to test.</p><p>Using Bunsen Burner,</p><pre>[Fact(DisplayName = &quot;Given tasks are cached, when get all endpoint is called, then must return tasks from the cache&quot;)]<br>public async Task GetAllTasksWhenCached() =&gt;<br>    await Given(() =&gt;<br>        {<br>            var fixture = new Fixture();<br>            return GetMockedQueryHandler(<br>                [],<br>                fixture.CreateMany&lt;TodoDataModel&gt;(5).ToList(),<br>                fixture.CreateMany&lt;TodoDataModel&gt;(10).ToList()<br>            );<br>        })<br>        .And(qh =&gt;<br>        {<br>            var client = factory<br>                .WithWebHostBuilder(builder =&gt;<br>                {<br>                    builder.ConfigureTestServices(services =&gt;<br>                    {<br>                        services.AddSingleton(qh.Object);<br>                    });<br>                })<br>                .CreateClient();<br><br>            return (queryHandler: qh, client);<br>        })<br>        .When(async data =&gt;<br>        {<br>            var httpResponse1 = await GetAllTasks(data.client);<br>            return httpResponse1;<br>        })<br>        .And(<br>            async (data, httpResponse1) =&gt;<br>            {<br>                var httpResponse2 = await GetAllTasks(data.client);<br>                return (httpResponse1, httpResponse2);<br>            }<br>        )<br>        .And(<br>            async (data, responses) =&gt;<br>            {<br>                var httpResponse3 = await GetAllTasks(data.client);<br>                return (responses.httpResponse1, responses.httpResponse2, httpResponse3);<br>            }<br>        )<br>        .Then(responses =&gt;<br>        {<br>            responses.httpResponse1.StatusCode.Should().Be(HttpStatusCode.NoContent);<br>            responses.httpResponse2.StatusCode.Should().Be(HttpStatusCode.OK);<br>            responses.httpResponse3.StatusCode.Should().Be(HttpStatusCode.OK);<br>        })<br>        .And(<br>            (data, _) =&gt;<br>            {<br>                data.queryHandler.Verify(<br>                    x =&gt; x.QueryAsync(It.IsAny&lt;SearchAllQuery&gt;(), It.IsAny&lt;CancellationToken&gt;()),<br>                    Times.Exactly(2)<br>                );<br>            }<br>        )<br>        .And(async responses =&gt;<br>        {<br>            var todoListResponse = await GetToDoListFromResponse(responses.httpResponse2);<br>            todoListResponse.Should().NotBeNull();<br>            todoListResponse!.Tasks.Should().NotBeNull().And.HaveCount(5);<br>        })<br>        .And(async responses =&gt;<br>        {<br>            var todoListResponse = await GetToDoListFromResponse(responses.httpResponse3);<br>            todoListResponse.Should().NotBeNull();<br>            todoListResponse!.Tasks.Should().NotBeNull().And.HaveCount(5);<br>        });</pre><p>The setup and the assertions are the same, and the test is more structured.</p><p>If you want to perform another setup or an assertion, the best approach is to simply use the “And” method.</p><p>If you want to extend the functionality simply create your own methods.</p><p><strong>Note: Please refer this </strong><a href="https://github.com/Cheranga/LetsDoIt/tree/main/tests/LetsDoIt.ToDoApi.BunsenBurner.Tests"><strong>project</strong></a><strong> for tests written using Bunsen Burner. Also I have created </strong><a href="https://github.com/Cheranga/LetsDoIt/tree/main/tests/LetsDoIt.ToDoApi.Tests"><strong>another test project</strong></a><strong> where some tests are written without using Bunsen, so that you could compare the approaches.</strong></p><h3>References 👏</h3><p>✅ <a href="https://github.com/bmazzarol/Bunsen-Burner">Bunsen Burner on GitHub</a></p><p>Please don’t forget to give a star ⭐ to the library if you like it!</p><h3>Feedback ❤</h3><p>If you have any feedbacks, or suggestions, please feel free to open an issue on the GitHub repository.</p><p>If you want to create a PR, please feel free to do so.</p><p>When you create the PR, please make sure to follow the guidelines provided in the repository.</p><p>Please run the below commands at the root level before creating a PR, as it will format the code, according to <strong>“CSharpier”</strong> rules.</p><pre>dotnet tool restore<br>dotnet husky install<br>dotnet husky run</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a71e73c954" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/bunsen-burner-set-your-tests-on-fire-d9a71e73c954">Bunsen Burner — Set your tests on fire! 🔥</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using asynchronous fluent validations in ASP.NET API]]></title>
            <link>https://medium.com/cheranga/using-asynchronous-fluent-validations-in-asp-net-api-831710b0b9cd?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/831710b0b9cd</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[fluentvalidator]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 09:34:27 GMT</pubDate>
            <atom:updated>2022-08-09T09:34:27.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ofWDRDb2--pYN6frN0GqXA.png" /><figcaption><a href="https://www.flaticon.com/free-icon/api_603197">Api — Free seo and web icons (flaticon.com)</a></figcaption></figure><h3>Context</h3><p>While at work, my friend <a href="https://github.com/bmazzarol">Ben</a>, and myself came across an interesting problem to fix, when upgrading our APIs to latest .NET and upgrading their respective packages.</p><p>Validation is crucial when designing APIs, and we are using the wonderful FluentValidation.AspNetCore in our APIs. How it seamlessly allow the engineers to define the validations, and integrate with the ASP.NET echo system is a breeze.</p><p>Some of our validators contain asynchronous validations, and after upgrading we got the below error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVmVa_WRLN-Ru1IByRBM8Q.png" /></figure><p>The error clearly states that our validators contain asynchronous validations, and the ASP.NET validation pipeline is not asynchronous and hence can’t invoke asynchronous rules.</p><p><strong><em>Yes, it can be debated that validations must be synchronous, but in reality there are many situations where certain validations have to be asynchronous, such as validating with a data store entry or with a web service. Also it can be the opinion, that such actions should be the responsibility of the core layer(application / domain), but this was existing code, and in our opinion the approach was correct ☺️</em></strong></p><p>The code for this article can be found in <a href="https://github.com/Cheranga/articles-fluentvalidation.api">GitHub</a></p><h3>Options Considered</h3><ul><li>Move the async validations from the validators, and move it to the application or the business layer.</li></ul><p>Then we will have to create another level of abstraction to be injected into the controller or the core layers, and to make changes to our existing validators and respective classes. Also we’ll lose all the “async” validations performed at the time of model binding.</p><ul><li>Implementing a custom action filter.</li></ul><p>This action filter needs to perform asynchronous operations, and should be able to use the existing validators without any code changes to them. At the time of execution it needs to be able to find the respective IValidator<br> and perform the validations, and most importantly if it contains validation errors to short circuit the ASP.NET pipeline.</p><p>💡 we chose to implement a custom action filter to perform validations.</p><h3>Demonstrating the problem, with a sample API</h3><p>This is an API to manage products. For the sake of brevity I have created only a single endpoint which simulates an adding of a product.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5adec9efc3d1a96960e0cc75a6bbb7e/href">https://medium.com/media/a5adec9efc3d1a96960e0cc75a6bbb7e/href</a></iframe><p>In the Program.cs we register the dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f58e73e26a9e9672196194ab7c520a/href">https://medium.com/media/03f58e73e26a9e9672196194ab7c520a/href</a></iframe><p>The Validator for the DTO</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4697367f91851b55b94feb9603a8e306/href">https://medium.com/media/4697367f91851b55b94feb9603a8e306/href</a></iframe><p>The action method which will expose the endpoint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/980e85e3d6898c612ff317a4ccf7d8a3/href">https://medium.com/media/980e85e3d6898c612ff317a4ccf7d8a3/href</a></iframe><p><em>Note that I have used another Nuget package called </em><em>HybridModelBinding to bind the model from different model binders and value providers.<br>As you can see below the DTO is getting populated by both from the header and from the body. Hybrid model binding is not relevant to the validations, but wanted to demonstrate that since the validation approach must happen after the model binding.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4014e5335389fd89d54dc54dd184baab/href">https://medium.com/media/4014e5335389fd89d54dc54dd184baab/href</a></iframe><p>When you run this project, and make an HTTP POST request to this endpoint, you’ll get the above mentioned error.</p><h3>Custom action filter to validate DTOs</h3><p>When designing the solution, we wanted to design, and implement the filter to be used with our many other APIs.<br>So we could make this as a common library such as a nuget package to be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/933c5592cc100ef2e3f9bc0031899689/href">https://medium.com/media/933c5592cc100ef2e3f9bc0031899689/href</a></iframe><p>Let’s explore what has been implemented in the action filter.</p><ul><li>Inject an ICustomValidatorFactory which will get the respective IValidator instance.</li><li>Implement the IAsyncActionFilter interface and it’s OnActionExecutionAsync method.</li></ul><p>In here for each action argument’s type it tries to get the respective IValidator instance if available. If a validator instance is available it will call it’s ValidateAsync method. The ValidateAsync method will perform both synchronous and asynchronous validations. Finally if there are validation errors it will use these validation errors to create a ProblemDetails response and set it in the action result and, short circuit the ASP.NET pipeline.</p><p>Please see the extension method to return ProblemDetails from ValidationFailures.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aa4638680ba1ccdce9b3171b885170d/href">https://medium.com/media/8aa4638680ba1ccdce9b3171b885170d/href</a></iframe><p>Most importantly let’s check the CustomValidatorFactory implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ca03b60b00ffe15cb4a52284cf8173/href">https://medium.com/media/33ca03b60b00ffe15cb4a52284cf8173/href</a></iframe><p>Let’s explore the validator factory now.</p><ul><li>An IServiceProvider is injected, this will be injected by ASP.NET itself.</li><li>We create an IServiceScope using the IServiceProvider because we wanted this code to be independent of how the actual IValidator instances are registered with the dependency injection for their lifetime.</li><li>Create an IValidator instance and return it.</li></ul><h3>Let’s put these all together</h3><ul><li>Extension method to register FluentValidators, and the CustomValidatorFactory</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dfb6fc365f630b74d8ed1ac628871f1/href">https://medium.com/media/6dfb6fc365f630b74d8ed1ac628871f1/href</a></iframe><p>Notice that there are two options which can be used, one with a single assembly and the other with a set of assemblies where the validators are located.</p><p>In Program.cs let’s use it. Note that the ApiValidationFilter has been registered in the controller configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e8cc95b31319f3fcc4be506b45fe31/href">https://medium.com/media/b9e8cc95b31319f3fcc4be506b45fe31/href</a></iframe><h3>Testing</h3><p>Please find the unit tests for this in the Demo.Products.Api.Tests project.</p><p>If you would like to run this project, and test I highly recommend the RestClient either in VSCode or in Rider. I am using Rider, and you can see the results below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*hqem7xZQiFvaE_dLNMScRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831710b0b9cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/using-asynchronous-fluent-validations-in-asp-net-api-831710b0b9cd">Using asynchronous fluent validations in ASP.NET API</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Database migrations with Azure Container Instances and DbUp]]></title>
            <link>https://medium.com/cheranga/sql-database-migrations-with-azure-container-instances-and-dbup-a2360df4ba84?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/a2360df4ba84</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[dbup]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 01:55:03 GMT</pubDate>
            <atom:updated>2022-07-02T02:03:20.155Z</atom:updated>
            <content:encoded><![CDATA[<p>When designing applications, having a data store is very common. Regardless of microservices or any other methodology you use designing the data store will be different compared to how you design your application.</p><p>Although the data store migration activities will be associated with your application changes, separating that from your application code is important, so that they can be treated separately.</p><p>In here we will be migrating a SQL database using Azure Container Instances.</p><p>The code for this can be found in <a href="https://github.com/Cheranga/Demo.Aci.DbMigrations">GitHub</a></p><h4>Azure Container Instances</h4><p>The database migration activities doesn’t need to be continuously monitored or running in the background. These activities are usually carried out at the start of the application.</p><p>Azure container instances is a perfect fit for this because,</p><ul><li>If you are designing systems using containers, you don’t want to deviate to a different strategy just to deploy your database migrations.</li><li>There is no need for container orchestrations.</li><li>A short lived activity, and you’ll be paying only for the time the container was running.</li><li>You can “choose” how much compute you will need (in this case we will be using 1 CPU and 1GB of memory).</li></ul><blockquote>Running a container in an ACI as a sidecar to your application will be the perfect scenario. In an another article will be covering that.</blockquote><p>For more detailed information about ACI please refer the <a href="https://docs.microsoft.com/en-us/azure/container-instances/container-instances-overview">documentation</a></p><h4>DbUp</h4><p>DbUp is a very nice little library where you can use .NET to write your database migration activities. It supports a wide variety of relational databases.</p><p>What I like most about DbUp is, you can write the database migration queries in the way you want. You have full control over the queries which you write, and DbUp will use your scripts to perform the migrations. If using entity framework&#39;s migration activities, you will need to write code to do that, but you will be unaware (or somewhat abstracted) about the real SQL queries generated to perform the upgrades. The next feature I like about DbUp is that how it keeps track of the queries/migration activities performed, and execute only what&#39;s necessary to upgrade the database.</p><p>I use a convention to name my queries like yyyyMMddHHmm-[query name].sql. In this way the queries are numbered and DbUp simply orders them and execute them in order. Simples!</p><h4>Application</h4><p>Let’s create a .NET 6 Console application, and add the below code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeb614f4317309765612055510db5292/href">https://medium.com/media/eeb614f4317309765612055510db5292/href</a></iframe><ul><li>The “database server name”, “database name”, “user name” and “password” are passed as environment variables. Not just the connection string. I have found passing these parameters separately rather than the full connection string is more secure, because then you don’t want to output the connection string from the deployed resource or do some other DevOpsy gymnastics just to get the connection string 😌</li><li>The database migration scripts are set as embedded resources, so that they will be part of the DLL itself. in this way no need to load the scripts from an external storage. Note that DbUp have few options how you can load your scripts to be executed.</li><li>All the scripts are executed as a transaction (WithTransactionPerScript).</li><li>return values are important, negative number represents a failure and zero represents a successful migration.</li></ul><p>The Docker file to create the image for the database migration (Thanks RIDER!)</p><pre>FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base<br>WORKDIR /app</pre><pre>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build<br>WORKDIR /src<br>COPY [&quot;BankingDataStore.Console/BankingDataStore.Console.csproj&quot;, &quot;BankingDataStore.Console/&quot;]<br>RUN dotnet restore &quot;BankingDataStore.Console/BankingDataStore.Console.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/BankingDataStore.Console&quot;<br>RUN dotnet build &quot;BankingDataStore.Console.csproj&quot; -c Release -o /app/build</pre><pre>FROM build AS publish<br>RUN dotnet publish &quot;BankingDataStore.Console.csproj&quot; -c Release -o /app/publish</pre><pre>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;BankingDataStore.Console.dll&quot;]</pre><p>To develop and test in your local environment, I created a Docker compose file so that it can be attached with your IDE. I am using JetBrains RIDER, and it seamlessly hooks up with the file and will give you the local debugging experience for your database migration activity.</p><pre>version: &#39;3.4&#39;<br>services:<br>  dbsetup:<br>    build:<br>      dockerfile: BankingDataStore.Console/Dockerfile<br>    restart: on-failure      <br>    depends_on:<br>      - database<br>    environment:<br>      SERVER_NAME: &quot;database&quot;<br>      USERNAME: &quot;sa&quot;<br>      PASSWORD: &quot;Pa55w0rd123!&quot;<br>      DATABASE_NAME: &quot;customeraccountsdb&quot;<br>    <br>  database:<br>    image: mcr.microsoft.com/mssql/server:2019-latest<br>    restart: always<br>    environment:<br>      ACCEPT_EULA: &quot;Y&quot;<br>      SA_PASSWORD: &quot;Pa55w0rd123!&quot;<br>    ports:<br>      - &quot;1433:1433&quot;<br>    volumes:<br>      - ./bankdata/data:/var/opt/mssql/data<br>      - ./bankdata/logs:/var/opt/mssql/log<br>      - ./bankdata/secrets:/var/opt/mssql/secrets</pre><h4>CI/CD with GitHub Actions and Azure Bicep</h4><p>Let’s create a CI/CD pipeline using GitHub Actions to deploy the database migrations in Azure.</p><p>The pipeline has been organized as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*GhWGwHaNmfqh9mpL.png" /><figcaption>CI/CD pipeline structure</figcaption></figure><p>The Azure Bicep templates are residing in a folder called templates and each Bicep template has it&#39;s own folder which represents the resource it will be deploying. The main.bicep template as per the name is the &quot;main&quot; template (😁) where it orchestrates the deployments.</p><p>Please refer the .github directory for these templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g60jU2kmkVExhO8AyK4eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*l5tPx7vlBce7Vo_w.png" /></figure><h4>Deployments</h4><ul><li>The resource group and the deployment histories are created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yX84_RX8rIZx5Aet.png" /></figure><ul><li>The ACI run, as you can see the migrations have been performed and the container instance is not running anymore (i.e the status is Terminated)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rF9KI09gVKZG4rf8.png" /></figure><ul><li>The database tables have been created as per the migration activities</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*NZJAFBJo8k_lpuoN.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2360df4ba84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/sql-database-migrations-with-azure-container-instances-and-dbup-a2360df4ba84">SQL Database migrations with Azure Container Instances and DbUp</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identity based triggers and bindings in Azure functions]]></title>
            <link>https://medium.com/cheranga/identity-based-triggers-and-bindings-in-azure-functions-d61c0d0ba60a?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/d61c0d0ba60a</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[azure-functions]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 21:20:06 GMT</pubDate>
            <atom:updated>2021-11-13T21:30:01.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*VsQgIRxQXR6ooBsqQ_B7IQ.png" /></figure><p>Azure functions are getting improved, and updated more frequently now. Recently it has been upgraded to support identity based triggers and bindings.</p><p>The Azure function will be provided only the required roles to access the resource so that its more secure. Although, still its always best to access sensitive data through a key vault if you cannot do so using identity based connections.</p><p>For an example, if you are implementing a service bus triggered Azure function without identity based connections, the connection to the topic had to be saved in a key vault and then provide access to the Azure function app to access the key vault through managed identity. But with the new changes now, you can use RBAC to provide access to the function app directly to access the service bus topic securely.</p><h3>Context</h3><p>In this demo we’ll be creating a service bus triggered Azure function with identity support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZDFpyE_IvOAqMmnNi111g.png" /></figure><p>All the code for this can be found in <a href="https://github.com/Cheranga/Demo.Identity.Functions/tree/master">GitHub</a>.</p><p>Once we deploy the Azure functions, and <strong>if we didn’t use identity</strong> based connections the configuration section in the Azure function app will look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G83_pTwssBzNjuTDupwMTw.png" /></figure><p>The setting <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-app-settings#azurewebjobsstorage">AzureWebJobsStorage</a>is required by Azure functions to perform normal operations, and as you can see the connection string to the storage account is visible. This is not secure.</p><p>Also if you can refer the other configurations marked in red boxes they represent the read/write access to the service bus to be used in the Azure functions. Although they are securely accessed through a key vault, it would be better if the function app itself have the required access to the service bus so that a key vault will be unnecessary in this case, and it will be more secure.</p><p>“More secure” also means that the actual value in the key vault can be anything, and it might not be the correct access connection string or it could be tampered. But with managed identity once the access is provided with the correct roles you don’t need to worry anymore.</p><h3>Design Principles</h3><p>When we design and build a solution we would like to use good design principles. Especially if you are following the S.O.L.I.D principles you will be decoupling responsibilities across multiple contexts. One context you will be considering here is decoupling infrastructure related implementations such as publishing to a service bus, event hub or to a database. Simply you should not be implementing it in the same presentation layer . That is, in Azure functions perspective where you define your Azure functions.</p><p>But with Azure functions output binding support, you will be tempted to bind the infrastructure component and then pass it down the layers where the actual operation happens.</p><p>This is how you would create a function which uses output binding and passes it through the lower layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCKzjKK30hWVoD0i9uPwYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*xBXB_tAWAwpVJw2e-2HRAQ.png" /></figure><p>The messages is an output binding and it’s passed down to the lower layers ( IReceiveOrderRequestHandler in the application/domain layer) to perform actions of it. This creates an unnecessary coupling in the application/domain layer where it directly coupled with a library and, the only reason to do this is to use the output binding support.</p><p>The Azure SDKs are frequently updating with improved features and support. In here we’ll be using the required SDK support in the infrastructure layer and, of course we’ll be using the identity support which are already available in those SDKs.</p><h3>Clean Architecture</h3><p>The solution is designed based on the clean architecture patterns and the solution is organized as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*K0_FvD-XTA5ckfhB9mi0qg.png" /></figure><h3>Infrastructure components</h3><p>Let’s emphasize on the infrastructure layer and as illustrated above the ReceiverOrderFunction will need to publish a message to the service bus topic. The publication of this message is implemented in the infrastructure layer.</p><h4>IMessagePublisher and MessagePublisher</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006b28e3dfebcb05c20e8511fb92a598/href">https://medium.com/media/006b28e3dfebcb05c20e8511fb92a598/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f434d3a6e013345824dcb7966290a378/href">https://medium.com/media/f434d3a6e013345824dcb7966290a378/href</a></iframe><p>The ServiceBusClient is from the nuget package Microsoft.Azure.WebJobs.Extensions.ServiceBus and you can register the client as a dependency in the Startup class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f4d81dcb73eb3d9daf82fb133c7169/href">https://medium.com/media/f5f4d81dcb73eb3d9daf82fb133c7169/href</a></iframe><p>When registering the service bus client we are explicitly stating to avoid the other authentication mechanisms. This is important so that the code will use only Azure CLI, and managed identity.</p><h3>Azure Functions (service bus triggered function)</h3><p>The service bus triggered function will be using identity based connectivity to get triggered. As you could see the code is not different to an implementation without identity based. It will be at the deployment stage that these access rights to be provided. This will be explained towards the <a href="# Providing RBAC access">end of this article</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00a09d804ac224190c4d4b0b77890e25/href">https://medium.com/media/00a09d804ac224190c4d4b0b77890e25/href</a></iframe><h3>Setting up your local environment</h3><p>Since the application needs access to both read and write from the service bus topic/subscription both the application and the user of the IDE needs to have Azure Service Bus Data Receiver and Azure Service Bus Data Sender roles assigned to them.</p><p>I was able to successfully “publish” messages to the topic using managed identity from my local environment but unfortunately I wasn’t able to “trigger” the service bus triggered Azure function in my local environment. So I had to use the service bus connection string <strong>“only”</strong> in my local environment.</p><p>The local.settings.json should be set as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qtmg_VaUdUa23XlZaBroBw.png" /></figure><h3>CI/CD</h3><h4>Build Pipeline</h4><p>In here we are using a YAML based multi-stage pipeline to build and deploy the solution to Azure. The resources to be deployed are declared using Azure Bicep .</p><p>The CI/CD pipeline, and how it’s organized is explained below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*fNtWerWag8Zxc8ahkqL2OQ.png" /></figure><h4><strong>pipeline.yaml</strong></h4><p>This contains all the stages and the environments which the pipeline will build and deploy the solution.</p><h4><strong>build.yaml</strong></h4><p>This is the build pipeline. All the steps required to build and test the solution along with the artifacts to be used in the deployment pipeline.</p><ul><li>Builds and restores the solution.</li><li>Run the tests in the solution if there are any.</li><li>Create the function app artifact to be deployed into Azure.</li><li>Create the Bicep templates as an artifact so that it can be referenced from the deployment pipeline.</li></ul><h4><strong>Variables</strong></h4><p>In this folder we will include all the variables to be used in the CI/CD pipeline. The variable files are named after the environment they will be used. There’s a file called common.yaml where you can define all the variables which can be shared among all the environments. The benefit of having such a file is that, then in the environment variable files you only need to define the variables which are specific to that environment or if there are values which you would like to be overridden from the common .</p><p>The common.yaml variable file,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*gj1jLJXX_RO0AKF-SHJY1w.png" /></figure><p>The dev.yaml variable file with it’s own variable declarations and the overridden value from the common.yaml variable file,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*pIHXB_SX1VXyJIPF_m72cQ.png" /></figure><p>Although we deploy only to the development environment (dev) you can add any environments as you would like.</p><h3><strong>Resources</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*mMeLhKqSQ23lmO4Rrr88Qw.png" /></figure><p>All the resources which will be used to deploy this solution has been organized into their own folder and inside it contains the Azure Bicep template which will be used to deploy the resource.</p><p>For an example the ApplicationInsights folder contains the bicep template which will be used to provision an application insights instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*cOBS7Ejq9ngSftKU5djktg.png" /></figure><p>Importantly when you are deploying the Azure function app settings you could notice that compared to the local.settings.json it uses “__” (double underscore). This is because in the bicep templates you cannot use “:” since it’s special but, delightfully you don’t want to change any of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*VwPyI9qWr3nQkhHf323MtA.png" /></figure><h4><strong>main.bicep</strong></h4><p>This is the master bicep template which will orchestrate all the other bicep templates which will be used to deploy the Azure resources. As you could see we use bicep modules feature to reference the resource templates and define dependencies. Azure Bicep has made this really convenient with the modules support.</p><p>You can do the same using ARM templates as well, but then you’ll need to use “linked ARM templates”, and to do that you’ll need to upload all the ARM templates to a storage location and access them through a SAS token in the deployment pipeline. This can be completely avoided by using bicep modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9701bdd9b6d89533ad3fc553c84694e/href">https://medium.com/media/c9701bdd9b6d89533ad3fc553c84694e/href</a></iframe><h3>Providing RBAC access</h3><p>Once all the resources are provisioned now the deployment pipeline needs to provide RBAC to the resources to collaborate.</p><ul><li>Need to assign Storage Blob Data Owner for the function app and its staging slot to access the storage account using managed identity.</li><li>Need to assign both Service Bus Data Receiver and Service Bus Data Sender roles to the function app so that it can publish and trigger from the service bus namespace topic and subscription.</li><li>These are done through Azure CLI in the deployment pipeline. Please refer the github repository but the code snippet which does this is shown below.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abefb97bcd01cb88a819bbaac92b7dac/href">https://medium.com/media/abefb97bcd01cb88a819bbaac92b7dac/href</a></iframe><p>When we provision the function app and its staging slot the deployment will output the resource ids of them as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5905fad36b862b0e3ddd3b30a027448/href">https://medium.com/media/d5905fad36b862b0e3ddd3b30a027448/href</a></iframe><p>So in the script above it uses this deployment as a reference and get the resource ids of both the function app and its staging slot, and then assign the required roles.</p><h3><strong>Deployed Azure function app and its settings</strong></h3><p>The configuration settings of the deployed Azure function app will be like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*IhUVG-GfKvKN9Do0JjTY-A.png" /></figure><p>As you can notice instead of AzureWebJobsStorage now it’s set as AzureWebJobsStorage_accountName and, as explained earlier the function app will have access to the storage account with that name using managed identity.</p><p>The configuration settings which are marked in a “yellow” coloured box represents the service bus namespace. As explained earlier, the ServiceBusConfig__FullyQualifiedNamespace will be used in the class which resides in the infrastructure of the project where as ServiceBusConnection__fullyQualifiedNamespace will be used by the service bus triggered function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61c0d0ba60a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/identity-based-triggers-and-bindings-in-azure-functions-d61c0d0ba60a">Identity based triggers and bindings in Azure functions</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Bicep and Azure DevOps to deploy a function app]]></title>
            <link>https://medium.com/cheranga/azure-bicep-and-azure-devops-to-deploy-a-function-app-a707c13b2bff?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/a707c13b2bff</guid>
            <category><![CDATA[azure-bicep]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure-devops]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 20:08:07 GMT</pubDate>
            <atom:updated>2021-06-17T20:31:01.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*hJH6QJDnL3zBSHLnTfzeqw.png" /></figure><p>I love “Infrastructure as Code because it provides you the luxury of making continuous improvements to your infrastructure by treating it as code. In reality, as developers we try to design and code to the best of our ability or come and refactor later. With IaC now we can do that for our infrastructure as well.</p><p>There are many tools which you can use to do that. This article is based on Azure and the default choice so far has been ARM templates . There are some other third party providers in the game as well such as Terraform, pulumi,etc...</p><p>This article is based on Microsoft’s new kid on the block for IaC.</p><p>🔥🔥🔥 Azure Bicep!</p><h4>Azure Bicep</h4><p>Bicep is a domain specific language which <strong><em>declares </em></strong>your Azure resources to be deployed. It provides uncomplicated syntaxes and have been designed to reuse the code very easily through modules.</p><h4>ARM templates Vs Bicep</h4><p>Simply put an ARM template is a json structured file which declares the resources and configurations.</p><p>We all have worked with ARM templates and one of its main “challenges” are depending on the resource you deploy you will need to know exactly what to configure and, this can be quite frustrating. Also since its JSON an ARM template can quickly turn into a one large file. Well as a solution that you can “modularise” your ARM templates using linked templates but to do that you will need to do some additional grunt work such as storing it in a storage and accessing it securely.</p><p>With Bicep, the syntax is very concise and clear. My favourite feature of it, support for “Modules” are there to organise your templates in a much re usable manner.</p><p>See the below Bicep template which will declare a consumption based app service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a97f217f02b77627a364c636c33a0e20/href">https://medium.com/media/a97f217f02b77627a364c636c33a0e20/href</a></iframe><p>In contrast to the previous, see the equivalent ARM template below,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9df6a359adc606f8c702ed7616e5380f/href">https://medium.com/media/9df6a359adc606f8c702ed7616e5380f/href</a></iframe><p>The Bicep template is very straight forward, where as the ARM template syntax you need to be very explicit about what you require.</p><h4>Bicep playground</h4><p>A good starting point will be the <a href="https://bicepdemo.z22.web.core.windows.net/">Bicep playground</a>. In there you can experiment with Bicep. The most important feature I like in there is that the ability to transform your existing ARM templates into Bicep . You can simply click the “<strong>Decompile</strong>” button and point to the ARM template. But be mindful that all your ARM templates might not be easily converted into Bicep templates. You just need to fix the errors which it will show you so generously.</p><h4>Required tools</h4><ul><li>VSCode</li><li>Bicep extension for VSCode</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeB1GS5T3qNXaSlOaTzDbA.png" /></figure><p>Absolutely love the Bicep extension! It has code snippets, syntax highlighting and, even intellisense!</p><p>You will find these features highly useful when building Bicep templates.</p><h4>Create an Azure function app using Bicep templates</h4><p>To create an Azure function app you will need the below resources.</p><ul><li>Resource group</li><li>Storage account</li><li>App service plan</li><li>App insights (optional but highly recommended)</li><li>Key Vault (optional)</li><li>Function App and its settings</li></ul><p>Now let’s create the above resources using Bicep!</p><h4>Storage account</h4><p>Let’s start with the storage account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8646370df086fda71b66e797dbcc4258/href">https://medium.com/media/8646370df086fda71b66e797dbcc4258/href</a></iframe><p>The storage account is so straight forward. You get the storage account kind and the storage account tier as parameters and use them to declare the storage account you require. Finally in the output section it outputs the connection string to the storage account.</p><p><strong><em>[ I didn’t know a way to get this connection string in a “declarative” fashion. But if you are aware of this please let me know in the comments. ]</em></strong></p><h4>Application service plan</h4><p>In here we’ll create a consumption based app service plan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee76cab0673206785d72544a56f038b/href">https://medium.com/media/fee76cab0673206785d72544a56f038b/href</a></iframe><h4>Application insights</h4><p>This is required so that you can review how good (or bad) your application is performing in Azure. Although this component is optional it’s highly recommended.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2ea33a3a6b99bc2bf4c2092cd886c1e/href">https://medium.com/media/f2ea33a3a6b99bc2bf4c2092cd886c1e/href</a></iframe><h4>Function app (without the settings)</h4><p>First let’s create the skeleton function app without the settings. The key vault (next step) will need to know the function app’s principalid and the tenantid to provide access.</p><p>The function app which we’ll be creating will use deployment slots (azure function apps supports production and staging slots only).</p><p>So the below Bicep template creates function app with the two slots. Since the AKV will need the principalid and the tenantid the template will output them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05bd57067cfa6fa7eac26870d64f59b/href">https://medium.com/media/d05bd57067cfa6fa7eac26870d64f59b/href</a></iframe><h4>Key vault</h4><p>Key vault is used to store sensitive data in a secure manner. In Azure, you can also specify who has access to the AKV. So in our case we would like to create an AKV but also we would like the function app to be able to access it securely.</p><p>We’ll be using MI (managed identity) to provide this link.</p><p>The below template is accepting the function app’s principalid and the tenantid to setup the access policies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3cdaae67311abece593049835c3f9be/href">https://medium.com/media/c3cdaae67311abece593049835c3f9be/href</a></iframe><p>Finally it outputs the URI (the latest version) of the secret to be used.</p><h4>Function app settings</h4><p>Finally let’s set up the configurations required for the function app. Since we have two slots (Production and staging) we’ll need two configuration sections to be setup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60657e2c3ece3f7a8ddd10159ed65be/href">https://medium.com/media/b60657e2c3ece3f7a8ddd10159ed65be/href</a></iframe><h4>We have the components, lets use them</h4><p>Now we have all the building blocks to create the function app. Bicep has this cool feature where you can create modules. Now let’s use Bicep modules to organise our resources to be deployed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f689fc0cc018e160774473f3a893db/href">https://medium.com/media/69f689fc0cc018e160774473f3a893db/href</a></iframe><p>This is the storage account module</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*JIl90_eaDyq_jQdtG2zoyg.png" /></figure><p>As you can see the syntax is very easy and straight forward. You define the module using the module keyword and the location for the Bicep template. Then you just simply pass the parameters required for the template. The Bicep extension of VSCode really helps you out here. As shown below the full intellisense is provided to you. It even give you a bunch of options including conditional access and my personal favourite required-properties .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EdvCIQKV20X50_-YxDDkw.png" /></figure><p>But when deploying the Azure resources you will need to know the dependencies between them when deploying. In our function app these are the dependencies when the Azure resources need to be deployed.</p><ul><li>Function app has dependencies on the storage account and the application service plan.</li><li>The key vault has a dependency on the function app because it needs to provide access to the function app.</li><li>The function app settings module has dependencies on function app, app insights and the key vault module.</li><li>The storage account, application service plan and the app insights modules does not have any dependencies.</li></ul><p>The dependencies among the Bicep modules are specified as DependsOn. The function app module dependencies can be defined as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*ASGet_OaLOM4LT7y-O0Npw.png" /></figure><h4>Azure DevOps</h4><p>Let’s create a YAML based multi-stage pipeline to build and deploy our function app.</p><h4>The CI (build) part</h4><p>This is the CI (continuous integration) part where you build and test your software before creating any artifacts to be deployed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f794618925147786ccb5775d8ccfc1/href">https://medium.com/media/57f794618925147786ccb5775d8ccfc1/href</a></iframe><p>The main purpose of a build pipeline is to check whether your code can be build successfully and to be able to create artifacts.</p><p>These are the steps associated with the build pipeline above,</p><ul><li>Build and restore your .NET projects.</li><li>Run the tests.</li><li>Create the function app artifact and package it as a zip.</li><li>Create the Bicep templates as an artifact so that they can be referenced easily in the deployment pipeline.</li></ul><h4>The CD (deploy) part</h4><p>This is the CD (continuous deployment) part where you deploy the artificats which were created as a result of the build.</p><p>The steps involved in the deployment pipeline are as follows,</p><ul><li><strong>Create the resource group.</strong></li></ul><p>We’ll use AZURE CLI to create the resource group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*apTAewGu1CIKQE3ZnnDmbQ.png" /><figcaption>Creating the resource group using Azure CLI</figcaption></figure><p>The resource group is created only if it doesn’t exist.</p><ul><li><strong>Provision the resources</strong></li></ul><p>We have the main Bicep template which orchestrates all the required resources to deployed in Azure. You can use the same Azure CLI command to deploy resources, az deployment group create here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*9sm483JCrN6_xAVDipNb0Q.png" /><figcaption>Passing parameters to the main bicep template to provision resources</figcaption></figure><p>Notice the --template-file argument. Since we created all the Bicep templates as an artifact with the name deploy (see the build pipeline above) we can easily use it to locate the Bicep template. Then all the parameters which are required by the main.bicep template is passed.</p><ul><li><strong>Deploy to the staging slot (stop + deploy latest code + start)</strong></li></ul><p>Since we are deploying an HTTP triggered function app with slots, we need to deploy our code to the staging slot first. Let’s stop it first, secondly we’ll deploy the latest code there and then start the staging slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*99U-OcllzsbAMA3Ruo5puw.png" /></figure><ul><li><strong>Deploy to the production slot (swap with staging + stop staging slot)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*rjwVHQVKayIIVSHzyIJkZA.png" /><figcaption>swap staging slot with production</figcaption></figure><p>Since the staging slot is up and running, we can perform the swap operation with the production slot as specified above. Once it’s done no need to keep the staging slot alive. So as the final step we can stop the staging slot.</p><h4>The CI/CD (build and deployment) pipeline</h4><p>Now we have a build pipeline and a deployment pipeline. In reality the applications we develop will be deployed in multiple environments. So let’s create the final piece where we can build and deploy the function app into multiple environments.</p><ul><li><strong>Trigger points</strong></li></ul><p>We’ll trigger the pipeline when the code is checked in to the master branch or to any branch under feature . Also for PR requests made comparing the code to the master branch <em>(you can make these conditional for each environment as well).</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db0180abc361427b8e11320939e0b7e9/href">https://medium.com/media/db0180abc361427b8e11320939e0b7e9/href</a></iframe><p>As you can see above there are multiple stages in the pipeline,</p><p>BUILD -&gt; DEV -&gt; SITare the stages in this pipeline, but you can create other environments as stages in the pipeline as you wish. Notice how the variable files are placed. There’s one common.yaml file to store all the parameters and each [env].yaml file to override the parameter values which will be specific to the environment.</p><h4>Setting up the pipeline in Azure DevOps</h4><p>Create a new pipeline in Azure DevOps, but since you already have the files required please select the file which has instructions to build and deploy your solution before you finish creating the pipeline in Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*rnBC61P-QVRf3v3TJ-KoqA.png" /><figcaption>Select the existing pipeline file in your solution.</figcaption></figure><p>After running the pipeline, you will be able to see the resources successfully deployed in Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmeTOb5_zF4UObu7a9vwMg.png" /><figcaption>The Azure DevOps pipeline</figcaption></figure><p>The created resource groups in Azure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ZzIoF-4c_oXFreHhVp4MEA.png" /><figcaption>The created resource groups</figcaption></figure><p>The deployment histories in resource groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYF0gA6XC3G0pTAC5sfbbA.png" /></figure><p>Finally, the resources deployed in the resource group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*yRKvZPoHJ6UDunC5mpCQaA.png" /><figcaption>The resources deployed in the resource group</figcaption></figure><h4>Conclusion</h4><p>Azure Bicep is awesome! The feature which I like most is the module support. VSCode and the Bicep extension is really helpful when you are building templates.</p><p>The code for this can be found in <a href="https://github.com/Cheranga/Demo.Bicep.Azure.Functions">GitHub</a></p><p><strong>Thanks!</strong></p><h4>References</h4><p><a href="https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/overview">Bicep language for deploying Azure resources - Azure Resource Manager</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a707c13b2bff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/azure-bicep-and-azure-devops-to-deploy-a-function-app-a707c13b2bff">Azure Bicep and Azure DevOps to deploy a function app</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Help me, to help you — helping Microsoft DI framework to find dependencies.]]></title>
            <link>https://medium.com/cheranga/help-me-to-help-you-helping-microsoft-di-framework-to-find-dependencies-a99d5c4bf55?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/a99d5c4bf55</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 01:35:56 GMT</pubDate>
            <atom:updated>2021-06-14T01:35:55.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Help me, to help you — helping Microsoft DI framework to find dependencies.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdptLofAUzx45aCxJELwpg.png" /></figure><p>This post is about dependency injection using Microsoft dependency injection framework. I use it a lot in my daily work and in personal projects.</p><p>When compared to its alternatives such as AutoFac or Ninject one of the missing features (as of now) is to “discover” the dependencies and register in the framework. For example, in Autofac it can scan through the assemblies and register your classes as their implemented interfaces or as self.</p><p>So in this post let’s try to help Microsoft.DependencyInjection framework to find our dependencies and register them as we would like to do.</p><p><strong>Context</strong></p><p>Consider you have a class and an interface which it implements.</p><pre>public interface IEmailService<br><em>{<br>    </em>Task<em>&lt;</em>bool<em>&gt; </em>SendAsync<em>()</em>;<br><em>}<br><br></em>public class EmailService : IEmailService<br><strong>{<br>    </strong>public Task<em>&lt;</em>bool<em>&gt; </em>SendAsync<em>()<br>    {<br>        </em>throw new System.NotImplementedException<em>()</em>;<br>    <em>}<br></em><strong>}</strong></pre><p>If this service to be injected we need to “explicitly” write the code to register it in the dependency injection framework. For example if we would like to inject as a Transient dependency, we would need to write the code below.</p><pre>// &quot;services&quot; is of type &quot;IServiceCollection&quot;<br>services.AddTransient&lt;IEmailService, EmailService&gt;();</pre><p>Now imagine depending on your solution it can have 10, 15 or more different abstractions and you “will” need to write similar code such as above to register the dependency of each and everyone of them. What we are trying to do here is to help the Microsoft dependency injection framework to find our dependencies and to register them once and for all.</p><h4>Approach</h4><p>In here we are going to implement a custom attribute to provide information about how we would like to inject our dependency. Then we’ll implement an extension method so that it can be used with Microsoft.DependencyInjection . You can do this in your application (API, Web, Console, etc..) itself or create a class library project. In either case make sure you have installed Microsoft.Extensions.DependencyInjection nuget package.</p><h4>Attributes</h4><p>Simply, attributes are to provide additional information at runtime. Depending on how you define the attribute usage (class level, property level, etc..) you can apply the attribute in your code.</p><h4>Extension Methods</h4><p>Extension methods are there to add custom methods to existing types. They are great if you would like to extend the functionality of a given type customized to your requirement.</p><h4>Let’s implement the attribute</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd7ebde46034a90b43c4e044fe21507/href">https://medium.com/media/3dd7ebde46034a90b43c4e044fe21507/href</a></iframe><p>The attribute can be used only in a Class level and its properties are,</p><ul><li>LifeTime</li></ul><p>This is of type ServiceLifeTime which is the type which is already defined in the Microsoft.Extensions.DependencyInjection framework.</p><ul><li>InjectAs</li></ul><p>This is an enum which will declare “how” you would like to inject your type. I have defined only two ways to inject the type and you can define any other type as you would like to be injected depending on your use case.</p><h4>Let’s implement the extension method</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42614fcc897c61a5db79a6552656ea6c/href">https://medium.com/media/42614fcc897c61a5db79a6552656ea6c/href</a></iframe><ul><li>Firstly it accepts a set of assemblies to scan for types.</li><li>Then for each type it checks whether it has the custom attribute InjectMeAttribute</li><li>Once it finds the types which have the InjectMeAttribute (candidate types) then it will check how it needs to be registered in the dependency injection framework.</li><li>We use the capabilities of Reflection and build the required types to be registered in the framework.</li><li>At the core of the dependency injection framework every dependency is defined as a ServiceDescriptor. So we use it to construct the source and target types and then register them in the dependency injection framework.</li></ul><h4>Using the attribute</h4><p>Considering the same example provided above now let’s decorate the EmailService class with our attribute.</p><pre><em>[</em>InjectMe<em>]<br></em>public class EmailService : IEmailService<br><strong>{<br>    </strong>public Task<em>&lt;</em>bool<em>&gt; </em>SendAsync<em>()<br>    {<br>        </em>throw new System.NotImplementedException<em>()</em>;<br>    <em>}<br></em><strong>}</strong></pre><h4>Using the extension method</h4><p>Let’s consider an ASP.NET Core Web API project to test this. In it’s ConfigureServices method in Startup.cs add the below method.</p><pre>services.RegisterDependencies(typeof(Startup).Assembly);</pre><p>You don’t need to define any dependencies “explicitly” as you did before for your classes anymore in the Startup class.</p><p>Whenever a type needs to be injected you just need to decorate it with the InjectMe attribute.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99d5c4bf55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/help-me-to-help-you-helping-microsoft-di-framework-to-find-dependencies-a99d5c4bf55">Help me, to help you — helping Microsoft DI framework to find dependencies.</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Functions — Validate Azure active directory tokens using your own custom binding]]></title>
            <link>https://medium.com/cheranga/azure-functions-validate-azure-active-directory-tokens-using-your-own-custom-binding-4b4ff648d8ac?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/4b4ff648d8ac</guid>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sun, 09 May 2021 01:21:57 GMT</pubDate>
            <atom:updated>2021-05-09T01:21:57.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Functions — Validate Azure active directory tokens using your own custom binding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*aOLvNQiCMaTg9803VcK0Ug.png" /></figure><p>Azure functions are great! but as in many frameworks there are times where you would like to extend or write your own custom logic to do what you are intending to do. It’s not about re-inventing the wheel of course, but how to use the underlying framework’s extension points so that you can build on top of that. So in this article let’s design and implement an Azure custom binding where you can use to validate JWT tokens issued by Azure Active Directory.</p><h4>What are we trying to achieve?</h4><p>Imagine that you are implementing an HTTP triggered Azure function and, you would like to secure it using AAD (Azure Active Directory)</p><p>Unlike ASP.NET Core Web APIs you don’t have rich features like Authorization Filters in Azure functions. So to authenticate and authorize your endpoints you will need to write code to handle that.</p><p><strong>Here are some of the options which we could use,</strong></p><ul><li>Implement a service to perform token validation and inject it as a dependency to your azure functions.</li><li>Deploy the azure function behind an APIM and add JWT validation policies.</li><li>Create our own custom Azure binding</li></ul><p>Although in my opinion the 2nd option is always something which we must do anyway. Implementing a service and injecting will be great, but if you have multiple Azure functions (either HTTP or some other trigger) implemented in the same class some of the Azure functions may not need authentication/authorization. But still it’s a good option.</p><p>In this article we’ll implement a custom <strong>Input Azure Binding</strong> which it will validate a token using AAD and will make available the ClaimsPrincipal from the token to be used inside the function if required.</p><pre><em>NOTE: With </em><a href="https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide"><em>Azure functions with .NET 5</em></a><em> you can implement your own custom </em><em>middleware like in ASP.NET Core (Will post an article about this in a later post). This articles focuses on Azure functions (V3) which are developed using .NET Core 3.x</em></pre><h4>The Azure function which we are going to secure</h4><p>To make this article focused on the custom input binding and the JWT validation let’s have the simplest HTTP triggered Azure function.</p><p><em>“It will do a fake 2 second delay and will return a string”</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c9e92a7d6d39c07fe22d8974245112/href">https://medium.com/media/47c9e92a7d6d39c07fe22d8974245112/href</a></iframe><p>As you can see the functions authorization level is set to anonymous so that we can control how the authentication/authorization is done.</p><h4>Implementing a custom input Azure function binding</h4><p>In here we would like to develop an input binding so that if the token is validated it will have a valid ClaimsPrincipal for us to use inside the Azure function.</p><ul><li><strong>Step 1 (Create the Attribute so various settings can be passed)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cc058b37edb82650b73791e2d00e369/href">https://medium.com/media/0cc058b37edb82650b73791e2d00e369/href</a></iframe><p>All the properties are decorated with the AutoResolve attribute so that these settings can be populated from the function configuration. The AuthorizeUrl is set to the well known url where it will be used to load the openid configuration data from AAD.</p><ul><li><strong>Step 2 (Implement the binding and letting Azure function runtime know about it)</strong></li></ul><p>By using IExtensionConfigProvider you can allow the Azure function runtime to use your code when it executes. This happens automatically in Azure function apps which are from V2 or above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d5de3c7d110fd7c980de53eb69147c/href">https://medium.com/media/68d5de3c7d110fd7c980de53eb69147c/href</a></iframe><p>In the preceding code it instructs the Azure function runtime to use the AzureAdTokenAttribute to populate the AzureAdToken instance.</p><ul><li><strong>Step 3 (Implement the token validation)</strong></li></ul><p>Let’s separate the token validation logic from the custom binding. As per the code above all the required configuration data to perform a token validation are inside the AzureAdTokenAttribute instance. But the token will be inside the HttpRequest . To have access to that when we implement the token validation service we’ll inject the IHttpContextAccessor . You don’t want to register this as it will be provided by the Azure function runtime itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3772c953c65d7396dedea385c87f59bd/href">https://medium.com/media/3772c953c65d7396dedea385c87f59bd/href</a></iframe><p>In the code above these are the actions it performs,</p><ul><li>It exposes a method called GetClaimsPrincipalAsync which accepts an AzureAdTokenAttribute instance.</li><li>From the injected IHttpContextAccessor it will get the Bearer token data from the Authorization HTTP header data.</li><li>It will use the passed AzureAdTokenAttribute configuration to get the OpenIdConfigurationData from the AAD so that it can validate the JWT token in AAD.</li><li>It uses the registered ISecurityTokenValidator from the Microsoft.IdentityModel.Tokens library to validate the token (you’ll see that we will be registering this dependency with JwtSecurityTokenHandler from the System.IdentityModel.Tokens.Jwt library in the Startup class later).</li><li>To validate the token parameters it will use TokenValidationParameters and below are the properties used to validate the JWT token.</li></ul><pre>var validationParameters = new TokenValidationParameters<br><strong>{<br>    </strong>ValidateAudience = true,<br>    ValidateIssuer = true,<br>    ValidateIssuerSigningKey = true,<br>    ValidateLifetime = true,<br>    RequireSignedTokens = true,<br>    ClockSkew = TimeSpan.Zero,<br>    <br>    ValidAudience = azureAdData.Audience,<br><br>    IssuerSigningKeys = openIdConnectConfigData.SigningKeys,<br>    ValidIssuer = openIdConnectConfigData.Issuer<br><strong>}</strong>;</pre><ul><li>Once the validation is performed and, if it’s valid then it’ll further check if any of the roles and scopes are available in the token. This is done only if they are defined in the passed AzureAdTokenAttribute itself.</li><li>If the token validation was successful then it will return the ClaimsPrincipal obtained from AAD. Otherwise it will return a null (<em>not a big fan of returning </em><em>null or throwing exceptions but in this case it makes sense to return </em><em>null because actually if the token is invalid there will be no </em><em>ClaimsPrincipal</em> ).</li></ul><p>Now use this service in your custom binding implementation,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d441aa08dbfa6b3f817cc704b9f6cb9a/href">https://medium.com/media/d441aa08dbfa6b3f817cc704b9f6cb9a/href</a></iframe><p>If the attribute data is not passed it will read it from the configuration data as shown in the GetAttributeWithRequiredSettings method.</p><ul><li><strong>Step 4 (Implement an extension method so that the binding and it’s related dependencies can be registered in one place)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5093b45f50b751ed2f2efd5f6ad944e1/href">https://medium.com/media/5093b45f50b751ed2f2efd5f6ad944e1/href</a></iframe><p>Most important to notice in here is that, this is an extension of the IWebJobsBuilder not the IFunctionsHostBuilder . The reason being we cannot register extensions using the AddExtension method being made available from the Azure function SDK (<strong><em>at least I couldn’t find a way, please let me know if we can do so</em></strong>).</p><p>the codebuilder.AddExtension&lt;AzureAdTokenBinding&gt; will register your custom binding with the Azure function runtime. Also as you can see the other dependencies which are used inside the custom binding are registered there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*hpaEtPRbRHfZ8mXrVG1VzA.png" /></figure><ul><li><strong>Step 5 (Let’s use the extension method in our startup)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80e67d7a8ebc260cb2df9300ff9d8a31/href">https://medium.com/media/80e67d7a8ebc260cb2df9300ff9d8a31/href</a></iframe><p>As you can see the Startup class implements IWebJobsStartup and registers the binding through the extension method.</p><ul><li><strong>Step 6 (Updating the configuration / local.settings.json)</strong></li></ul><pre><strong>{<br>    </strong>&quot;IsEncrypted&quot;: false,<br>    &quot;Values&quot;: <strong>{<br>        </strong>&quot;AzureAd:TenantId&quot;: &quot;[YOUR TENANT ID]&quot;,<br>        &quot;AzureAd:ClientId&quot;: &quot;[THE CLIENT ID OF THE APP WHICH USES THE SERVICE]&quot;,<br>        &quot;AzureAd:Instance&quot;: &quot;https://login.microsoft.com/&quot;,<br>        &quot;AzureAd:Audience&quot;: &quot;[THE APPLICATION ID OF THE SERVICE WHICH THE CLIENT IS ACCESSING]&quot;,<br>        &quot;AzureAd:Scopes&quot;: &quot;access.bff, test.bff&quot;,<br>        &quot;AzureAd:Roles&quot;: &quot;sales.bff.orders.search&quot;,<br>        &quot;AzureWebJobsStorage&quot;: &quot;UseDevelopmentStorage=true&quot;,<br>        &quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;dotnet&quot;<br>    <strong>}<br>}</strong></pre><h4>Using the custom binding in your Azure function</h4><p>Now finally, let’s use the custom binding which we implemented in our HTTP triggered Azure function.</p><ul><li><strong>Use case 1 (we just need a valid token)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ec1454731f94d3734ea971db052f19/href">https://medium.com/media/08ec1454731f94d3734ea971db052f19/href</a></iframe><p>You just need to add an AzureAdToken and decorate it with the AzureAdTokenAttribute . Since we just need to have a valid token we don’t need to pass any other parameters.</p><ul><li><strong>Use case 2 (Specific roles and scopes)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a05d9d2d082e19423a1c1e7ee16eebc4/href">https://medium.com/media/a05d9d2d082e19423a1c1e7ee16eebc4/href</a></iframe><p><em>If you just need either roles or scope, just pass an empty string or a null as the parameter.</em></p><ul><li><strong>Use case 3 (Want to load configurations from other configured sections)</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fc86e917d3af1ede79dcacb6c7d1f11/href">https://medium.com/media/7fc86e917d3af1ede79dcacb6c7d1f11/href</a></iframe><p>In the preceding code we will be loading the required data from different sections in the configuration like SomeOtherSection and AnotherSection (I am sure that you can come up with better names than me 😆)</p><p>The code for this can be found in <a href="https://github.com/Cheranga/Funky.Security">GitHub</a></p><h4>Conclusion</h4><p>Using Azure functions custom binding feature we can extend and implement our own features quite easily. Please feel free to add your inputs, comments, critics here.</p><p>Thank you!</p><h4>References</h4><p>Please refer the README in the repository for references and fixes which you may encounter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b4ff648d8ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/azure-functions-validate-azure-active-directory-tokens-using-your-own-custom-binding-4b4ff648d8ac">Azure Functions — Validate Azure active directory tokens using your own custom binding</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing and accessing APIs with Azure Active Directory (No secrets!)]]></title>
            <link>https://medium.com/cheranga/securing-and-accessing-apis-with-azure-active-directory-no-secrets-1dfef31eeace?source=rss----9d9327d82c31---4</link>
            <guid isPermaLink="false">https://medium.com/p/1dfef31eeace</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Cheranga Hatangala]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 10:29:25 GMT</pubDate>
            <atom:updated>2021-04-25T10:29:25.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>It’s always a best practice to secure the APIs (or any other resource) once deployed into the cloud.</p><p>In here let’s build a set of APIs which will be deployed to Azure and, make them accessible to each other securely.</p><h4>Scenario which we’ll be designing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4XbpWU2FQhVW-dUpRqijQ.png" /><figcaption>API design</figcaption></figure><p>A popular API design pattern is backend for front end (BFF). The design pattern is there to define a service (BFF) which will communicate with one or more services to provide a response, rather than allowing the clients to call multiple services. This will be highly beneficial to the client because otherwise it might need to maintain different settings to call each service and how and which endpoints to deal with. Also from a security perspective what if one or more of these APIs should not be made accessible to the clients directly at all? So the BFF will abstract all these services and will provide a single point of entry to the client.</p><p>In this scenario, we would not like to expose our internal APIs ( Orders API and Products API ) but only to be accessible through a BFF.</p><h3>Apps and roles in Azure Active Directory (AAD)</h3><p>Since we have three different APIs (BFF, Orders and Products) we need to create three different APP registrations in AAD. After the registrations are done we can independently create roles defined individually for the respective apps.</p><ul><li>Let’s first register an app to represent the BFF</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*SMV5V4ZDHDIPq8XxwHZOMQ.png" /></figure><p>In our case we only need one role to be defined in the BFF</p><ul><li>Search for a specific order by id</li></ul><p>There are two ways which you can create roles. Using the App Roles UI (preview at the time of writing) and App manifest editor . Let’s use the APP roles UI to define the roles. You can read more on this from <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*g7t_i0dqzqo_1I-vKX3sNQ.png" /></figure><p>Note that we want the BFF to be accessible by both Users and Services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*S02KOQMUpWS-sOC-Wm4lXQ.png" /><figcaption>Creating roles for BFF.</figcaption></figure><p>Then set the accessTokenAcceptedVersion to 2 because we would like to use OAuth V2 tokens for more fine grained security and control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*mROYCGrB3I2tJQiWtj2-1A.png" /></figure><p>Once done you’ll be able to see the roles for the BFF . Notice that the Allowed member types has been set to both Users/Groups, Applications .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azLoSWmQYn2aCKhnCPsUFQ.png" /></figure><h4>Setting application IDs</h4><p>Let’s try to avoid creating client ids and secrets in the first place. When we have client ids and secrets to maintain it creates an extra burden of maintaining them so let’s avoid them whenever we can.</p><p>So as the first step towards it we will need to setup Application ID URI for all the apps which we created. You can do them as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*kPT5dgFpxvIEZ3c_R7w6Bg.png" /></figure><p>Make sure you provide a meaningful name for the application ids.</p><h4>Getting a token to access the BFF securely</h4><p>Now let’s try to get a token to access the BFF securely. In here I am using Azure CLI</p><pre>az account get-access-token --resource api://app.secure.sales.bff.api</pre><p>But once executed we will be getting the below error,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZOLRkT_hYbjTVDwwnAFGg.png" /></figure><p>So what’s wrong here? We are logging in to a client application (in this case Azure CLI) and through that to get a token to the BFF . Remember that BFF is supposed to be accessible for users. So what’s the problem here? The problem in here is if the app needs to be accessible to users the app must have one or more scopes and a scope must be associated with the specific client.</p><p>So as you can see from the above error message it mentions that the application (Azure CLI) with id <strong>“04b07795–8ddb-461a-bbee-02f9e1bf7b46&quot; </strong>does not have rights to get a token. So let’s create a default scope called access.bff and assign it to the AZ CLI application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP2bgLR0WOvA1ZuQkVJpbg.png" /><figcaption>Adding a scope to the BFF.</figcaption></figure><p>Then add the client application as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSYVdjuu3Yby0jbrGdESWA.png" /><figcaption>Adding a client application to access the BFF.</figcaption></figure><p>Now let’s try to get a token again for the user. Use the same AZ CLI command to get a token for BFF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*2xtPCktbh7gpFiTVPUgsRA.png" /></figure><p>This time it’s a success! But let’s see what is inside the token. Browse to jwt.ms or jwt.io and copy paste the token to see what’s inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOsD0353xsQDqQYFL56_rQ.png" /><figcaption>The token obtained through AZ CLI.</figcaption></figure><p>As you can see the token contains the correct audience for the BFF and the scope. But as you can see there are no roles assigned to this user and, that’s because we haven’t assigned any to the user.</p><h4>User groups and users</h4><p>Rather than assigning roles to individual users it makes sense to create a user group and add the users to the group. Then assigning the user group the required permissions. But depending on your Azure subscription you might not have rights to create user groups (sadly like me 😞). But most likely in an enterprise setup you will be able to do so.</p><p>So said that, I am going to assign roles to my user to access the BFF. Go to the Enterprise applications in AAD and add the user as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pO7C4nZXXCER0EtPDeSNCg.png" /><figcaption>Adding a user with role.</figcaption></figure><p>Once done, you’ll see that the user now have the required role to access the BFF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xacaWQHaLRdr1uYOwYE0A.png" /></figure><p>Now let’s get an access token to the user and, inspect what’s inside there now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTASh32Zg6dJApkfzEKPuQ.png" /></figure><p>As you can see now, the user have a role, but also the scope from the client application (AZ CLI) which it used to get the token for the BFF .</p><h4>Building and securing the BFF API</h4><ul><li>Create an ASP.NET Core Web API project and add a controller called SalesController as shown below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*ZWJundU9fleRDfTJpmQBIQ.png" /></figure><p>As you can see the action method to get orders have been made secure using the attribute Authorize but also making it specific to the role sales.bff.orders.search . Meaning this action method will be authorized to be accessible through a sales.bff.orders.search role only.</p><p>But this is authorization, how can we make sure the authentication and the token sent are valid? For that we use the latest MSAL library from Microsoft.</p><p>Install the nuget package microsoft.identity.web and then add the below code in the Startup.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjZp9RDRHWVNLlp4JBXGrA.png" /></figure><p>You will need to setup the configuration inside the appsettings.json file as shown below. Please read more information about this in the microsoft documentation <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*VsVPMuXsv5LvVt_1MrKLsQ.png" /></figure><p>In here the Audience and the ClientId are set to the ClientId of the BFF app registration as shown below. Because we would like to validate the token for the BFF not for something else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*xH-CiJL4tj2gM9OAEkOafQ.png" /></figure><p>In the Configure method inside the Startup.cs register the middleware to authenticate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*oad9iXPMfO1gH7IPrlcczg.png" /></figure><p>Now get a token and access the web API. As you can see you’ll be able to securely access the BFF endpoint now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGQ-VYiKtrBj9pYyYzrrBA.png" /></figure><h4>Deploy BFF and verify it can be accessed securely</h4><p>It would be great to create separate deployment pipelines for these APIs. But to keep things focused on the security aspects let’s deploy through RIDER or Visual Studio to Azure.</p><p>Once deployed check if you can access the BFF API securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyT17Xp9hW0uRudu19S0Og.png" /></figure><p>So far we have been able to create an AAD app which represents the BFF and its respective roles. We also deployed the BFF API to Azure. Also we have been able to obtain an access token to a user to access the BFF securely.</p><h3>Azure active directory setup for orders and products</h3><p>As explained earlier the BFF needs to access both Orders and Produts APIs securely to provide a response to the callers.</p><p>First let’s create the respective roles for Sales and Products APIs.</p><p><strong>Sales setup</strong></p><ul><li>Create the role</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jOAXXOdm50fpxuPYjhw_7w.png" /><figcaption>Creating roles for orders app.</figcaption></figure><p><strong>Products Setup</strong></p><ul><li>Create the role</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*OHI1GZAXPLl-ThdLnCGE4A.png" /></figure><p>Please make sure that you have set the accessTokenAcceptedVersion to 2 for all the app roles in the manifest for both Orders and Products setup and select Applications for the Allowed member types .</p><h4>Let’s build and deploy Orders and Products APIs</h4><p>Now as we did for the BFF let’s build and deploy the Sales and Products APIs.</p><p>The action methods in both Orders and in Products API are very simple.</p><ul><li>Orders API</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*2ACqVXGZe9_mbE2BiuFFHQ.png" /></figure><p>The action method is secured through the role orders.search which we defined when we did the app registration and, below is the configuration which you’ll need to setup to validate the token sent to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Ap8k64Bfik8aOyF0xkDB4g.png" /><figcaption>Configuration for orders API to validate token</figcaption></figure><ul><li>Products API</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*E7elea4c28XxZWyphzP2Aw.png" /></figure><p>The action method is secured through the role products.search . Also the configuration to validate the token is as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*pgDwqYTpVonI3Fw5sJGpBQ.png" /></figure><p>Once deployed you will not be able to access the Orders or the Products APIs since they are secured and are accessible only through applications.</p><h4>Enabling BFF to access Orders and Products API through managed identity</h4><p>In the recent past we had to create client id and client secret to access Azure services securely. But with the introduction of the awesome managed identity that is no longer the case.</p><p>Let’s assign BFF the required roles to access the orders and products APIs.</p><p>Browse to the BFF API in your Azure resource group and set the managed identity as shown below. Note that I have created a System assigned managed identity here, but feel free to create a user assigned identity if you would like but the concepts will be the same. This can be easily automated through ARM templates in your deployment pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*XEMOfZTKjf5o_z3VCAe7qw.png" /></figure><p>This will result in an Enterprise application creation in your AAD and you will not be able to see any permissions assigned there yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*aNAt_SFASJLrXCIlpUl7LQ.png" /><figcaption>In enterprise applications.</figcaption></figure><p>Do the same for the Orders and Products APIs.</p><p><strong>Assigning the role to BFF to access the Sales API securely</strong></p><p>Let’s use powershell to do this easily.</p><ul><li>Connect to Azure</li></ul><pre>Connect-AzureAD -TenantId [your tenant id]</pre><ul><li>Get the client object id</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*yTV-snyEEjon8PEX7V0gAQ.png" /></figure><pre>$clientObjectId = &quot;b3aa2988-a695-45f1-ad4b-6da6e3dec4b4&quot;;</pre><ul><li>Now we’ll need the object id in the Enterprise applications</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*QNkWa2gRc496VPcEi8BzcA.png" /></figure><pre>$enterpriseObjectId = &quot;ee942677-0ed1-4971-b934-9571c2bd7ee2&quot;;</pre><ul><li>The role which we are going to assign,</li></ul><pre>$appRoleName = &quot;orders.search&quot;;</pre><ul><li>Get the client using the object id</li></ul><pre># Get the client api<br>$client = Get-AzureADServicePrincipal -ObjectId $([GUID]$clientObjectId);</pre><ul><li>Get the target application</li></ul><pre># Get the resource<br>$resource = Get-AzureADServicePrincipal -ObjectId $([GUID]$enterpriseObjectId)</pre><ul><li>Get the app role information,</li></ul><pre># Get the app role information<br>$appRole = $resource.AppRoles | Where-Object { $_.DisplayName  -eq $appRoleName }</pre><ul><li>Now assign the app role to the BFF API to access the Orders API</li></ul><pre># Assign the approle<br>New-AzureADServiceAppRoleAssignment -ObjectId $client.ObjectId -Id $appRole.Id -PrincipalId $client.ObjectId -ResourceId $resource.ObjectId</pre><p>Once done you’ll be able to see that now the BFF has been assigned the orders.search role to access the Orders API .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBVaOMhdnCFKJXBGYkEF7Q.png" /></figure><p>Now let’s see if we can access the Orders API from the BFF API . Let’s do some coding!</p><h4>Accessing the Orders API securely from BFF API</h4><ul><li>Install the microsoft.extensions.http package. Let’s create a typed HTTP client to access the Orders API securely.</li><li>Create a configuration entry to access the orders api</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Hti-bhEV-JwhC9DSUFQFVQ.png" /></figure><ul><li>Create a configuration class to map these</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*dAF4SA1lH9ojRMNJdBn6uw.png" /></figure><ul><li>Create a typed HTTP client class</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71321de42c35f2b4ead47fa6aef4255a/href">https://medium.com/media/71321de42c35f2b4ead47fa6aef4255a/href</a></iframe><p>Notice inside the GetAccessTokenAsync method we are using the ManagedIdentityCredential . You can use the DefaultAzureCredential class as well, which will try to get the access token from different sources. But in here we don’t want that and, also we want to specifically access through managed identity.</p><ul><li>Inject the service to the controller and modify the action method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*wMgm1xnlMRX8OFNEvKT4IA.png" /></figure><p>For us to understand what’s the token looks like when obtained through managed identity I am returning the token as well as part of the response. (This is purely for demonstration purposes! 😆)</p><ul><li>Deploy the BFF and access the endpoint using an access token,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2ofwJAl53jXNjP2dlrU6A.png" /></figure><p>If you inspect the token you’ll see that it has the value orders.search under roles</p><h4>Accessing the Products API securely from BFF API</h4><p>Please follow the same steps to assign the role products.search to the BFF and do the necessary code changes to access the products API as we did to access the orders API as well.</p><p>To demonstrate the different tokens obtained and to access the Products API changed the action method in BFF to return both tokens and the data from the two APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*WXHeNflSYOPI3LpWXhBaLw.png" /></figure><p>Once deployed you’ll be able to access both the Orders API and the Products APIs securely from the BFF API .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDCq_Bz6o30eL_eVhEu3Pg.png" /></figure><p>After analyzing the different tokens obtained by the BFF to access the Orders API and the Products API you’ll be able to see that they have the respective roles assigned in the tokens.</p><h3>References</h3><ul><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps">https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps</a></li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration">https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration</a></li><li><a href="https://www.youtube.com/watch?v=3PyUjOmuFic">https://www.youtube.com/watch?v=3PyUjOmuFic</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfef31eeace" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cheranga/securing-and-accessing-apis-with-azure-active-directory-no-secrets-1dfef31eeace">Securing and accessing APIs with Azure Active Directory (No secrets!)</a> was originally published in <a href="https://medium.com/cheranga">Cheranga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>