<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Collins on Medium]]></title>
        <description><![CDATA[Stories by Michael Collins on Medium]]></description>
        <link>https://medium.com/@mfcollins3?source=rss-4d3e14d1e5d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bHjn0lm1Bva9eQa5.JPG</url>
            <title>Stories by Michael Collins on Medium</title>
            <link>https://medium.com/@mfcollins3?source=rss-4d3e14d1e5d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:20:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mfcollins3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducing Easy Auth Simulator for Azure Developers]]></title>
            <link>https://medium.com/@mfcollins3/introducing-easy-auth-simulator-for-azure-developers-cb51eea67deb?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb51eea67deb</guid>
            <category><![CDATA[azure-app-service]]></category>
            <category><![CDATA[azure-container-apps]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 22:11:50 GMT</pubDate>
            <atom:updated>2026-09-21T03:20:34.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-g7aXn3Wj7rcqeiWLUFWg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">FlyD</a> on <a href="https://unsplash.com/photos/red-padlock-on-black-computer-keyboard-mT7lXZPjk7U?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Azure is a great platform for building applications, but some features are hard to develop for because they cannot be reproduced locally. In this post, I introduce Easy Auth Simulator to make it easier to build and debug applications that use the built-in application authentication services.</p><p>I really like Microsoft’s Azure cloud as a developer platform, but it was not always that way. I originally started out on AWS and was an AWS diehard, but over time, Microsoft has led me away from AWS and I’ve spent a significant time building applications for Azure. Like other technologies, I spend a lot of time really researching how to maximize the use of the services that I use. One service that I have found very helpful is the built-in Authentication service offered by Azure App Service, Azure Functions, Azure Container Apps, and Azure Static Web Apps.</p><p>The built-in Authentication service introduces a sidecar reverse proxy into your solution that sits between your application and the Internet (or intranet). All requests pass through the Authentication service and are forwarded to your web application. If a request requires that the user be authenticated, then the Authentication service will handle that and will only forward authenticated requests to the web application. User information including access tokens or ID tokens are forwarded to your web application or API as HTTP headers. The benefit of using the Authentication service is that it is compatible with any OpenID Connect service and has built-in support for popular providers such as Entra ID and Google. It takes authentication out of your web application, making life significantly easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gNzYGkz3hyUSlDWN" /></figure><p>(Source: Microsoft; <a href="https://learn.microsoft.com/en-us/azure/container-apps/authentication">https://learn.microsoft.com/en-us/azure/container-apps/authentication</a>)</p><p>Yet even this cool service has one problem: there’s no way to develop locally or debug locally. The Authentication service only runs in Azure. If your application is dependent on identity information or the access token to call APIs, you have to figure out some way to get that information injected into your app. Often, this means that teams don’t use this built-in functionality and implement authentication on their own because does not have a local emulator available… <strong>until now!</strong></p><p>This has been on my to do list for quite a while, but I finally got down to building it out. I am happy to introduce my <a href="https://github.com/mfcollins3/easyauthsimulator"><strong>Easy Auth Simulator</strong></a><strong> </strong>with<strong> </strong><a href="https://aspire.dev/"><strong>Microsoft Aspire</strong></a> support! Easy Auth Simulator is distributed as a Docker container image that can be downloaded and run locally. But it’s the Aspire support that makes this very simple to use with your own code. (If you are not using Aspire for application development, you really need to check this thing out.) With Aspire, you can configure the Easy Auth Simulator support with one or more web applications or APIs in your solution. You can easily use the Aspire integration support to configure authentication providers and add Azure-simulated authentication support to your applications. You can then use the access tokens to do real API testing. Easy Auth Simulator works with web applications or API servers written in any programming language. Because it runs as a sidecar process, it is completely independent from what you choose to build your application in. Whether you’re using Node.js with Next.js and React, Go, <a href="http://asp.net/">ASP.NET</a> Core, or Phoenix Framework with Elixir, you can use Easy Auth Simulator!</p><h3>Getting Started</h3><p>In the rest of this post, I will go into how to use Easy Auth Simulator to add authentication to a web application using Aspire.</p><h4>Prerequisites</h4><ul><li><a href="https://nodejs.org/">Node.js</a> (recommend 24+)</li><li><a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure CLI</a></li></ul><h4>Create a GitHub Personal Access Token</h4><p>I am currently publishing and hosting releases of Easy Auth Simulator to GitHub Packages. Both the Docker container image and the NuGet package containing the Aspire integration are published there. While the Docker container image should be downloadable anonymously, downloading NuGet packages requires a personal access token (PAT) from GitHub. You will need to create a classic PAT from GitHub with read:packages scope. (Fine-grained tokens aren&#39;t supported for package installs yet).</p><h4>Configure the NuGet Package Source</h4><p>Once you create the personal access token, you need to register my NuGet feed with your development environment as a package source. You can do that with the following command:</p><pre>dotnet nuget add source https://nuget.pkg.github.com/mfcollins3/index.json \<br>  --name mfcollins3-github \<br>  --username PUT_GITHUB_USERNAME_HERE \<br>  --password PUT_GITHUB_PAT_HERE \<br>  --store-password-in-clear-text</pre><p>This command will register my NuGet feed on your local machine so that you can install NuGet packages from my feed.</p><h4>Install the Aspire CLI</h4><p>We will be using the Aspire CLI to set up the project and run the web application that we develop in this post. Follow the <a href="https://aspire.dev/get-started/install-cli/">installation instructions</a> to download and install it on your machine.</p><h3>Using Easy Auth Simulator</h3><h4>Create an Aspire Project</h4><p>The first step is to get our web application started. We will begin by creating the Aspire AppHost that is used to orchestrate and run the solution containing the web application. The AppHost provides instructions to Aspire on what the different components of your solution are and how they are related. This allows Aspire to orchestrate the services at runtime and help with services such as service location or injecting configuration settings like database connection strings into the applications.</p><p>To begin, open a terminal and navigate to the location where you want to host the solution. Run:</p><pre>mkdir my-solution cd my-solution</pre><p>Now in this empty directory, run the Aspire CLI to initialize the AppHost for your solution:</p><pre>aspire init</pre><p>This command will ask you a few questions to help you to set up your solution. If you’re using an AI agent (I recommend you do), enable the AI skills <strong>(including the </strong><strong>aspirify skill) </strong>and Aspire MCP server. In this example, I am going to be using the TypeScript AppHost, but you can also use C# if you would like to.</p><p>Running the aspire init command gives us a working, but empty, application. We can run it, but there&#39;s nothing to do other than to start the Aspire AppHost and dashboard. We&#39;ll fix that next.</p><h4>Create a Web Application</h4><p>We’re going to start by adding a simple starter web application to the solution. This application will not have authentication support to start, but we will add it soon. We’re going to go simple and create a <a href="https://nextjs.org/">Next.js</a>/ <a href="https://react.dev/">React</a> application. In the terminal, run:</p><pre>npx create-next-app@latest web --yes</pre><p>You can see this app run on its own by running:</p><pre>cd web<br>npm run dev</pre><p>The app should be accessible at <a href="https://localhost:3000/">https://localhost:3000</a>.</p><h4>Add the Web Application to the AppHost</h4><p>We are now going to add the web application to the Aspire AppHost. When we run the AppHost, Aspire will start the web application and manage its execution. Aspire has an excellent dashboard that we can use to monitor all of the applications and services in our solution when running locally.</p><p>Open apphost.mts and add your web application:</p><pre>import { createBuilder } from &#39;./.aspire/modules/aspire.mjs&#39;; <br><br>const builder = await createBuilder(); <br><br>const web = await builder<br>    .addNextJsApp(&#39;web&#39;, &#39;./web&#39;)<br>    .withBrowserLogs();<br><br>await builder.build().run();</pre><p>If you want to test this now, you can change the last block to give the web application an external HTTP endpoint to browse to:</p><pre>const web = await builder<br>    .addNextJsApp(&#39;web&#39;, &#39;./web&#39;)<br>    .withExternalHttpEndpoints()<br>    .withBrowserLogs();</pre><p>Then you can run Aspire and see it:</p><pre>aspire run</pre><h4>Add Easy Auth Simulator to the AppHost</h4><p>Now we’re going to add authentication in front of the web application. To start, you will need to install the Easy Auth Simulator integration to your Aspire AppHost. In the terminal, run:</p><pre>aspire add EasyAuthSimulator.Hosting \<br>  --version 0.2.0 \<br>  --source mfcollins3-github</pre><p>Once this is done, we can now use the integration in the AppHost. Let’s add the Easy Auth Simulator to the bottom of apphost.mts:</p><pre>await builder <br>    .addEasyAuthSimulator(<br>        &#39;web-auth&#39;, <br>        { <br>            port: 8080, // pins the HTTP port to 8080 for OAuth 2 redirects<br>            authenticationRequired: true, <br>        }, <br>    ) <br>    .withUpstream(web) <br>    .withExternalHttpEndpoints();</pre><p>This new command tells the AppHost to start Easy Auth Simulator as a reverse proxy for the web application. All requests sent to http://localhost:8080 will be forwarded to the web application. The port specified pins the Easy Auth Simulator to that port. This is necessary because you are going to specify this port in your redirect URLs to the OpenID Connect providers and the port cannot be randomly allocated by Aspire. I&#39;m also using withExternalHttpEndpoints to tell Aspire that the Easy Auth Simulator should be externally accessible.</p><p>We’re almost there, but we need to add an identity provider to authenticate against. We will do that in the next section.</p><h3>Authenticating with Entra ID</h3><p>Our first example will show how to set up Easy Auth Simulator to authenticate against Microsoft’s Entra ID service. This is important for use in enterprise applications running in corporate networks. You will first need to register an application in Azure or Entra admin center, then we will register that application with Easy Auth Simulator.</p><h4>Registering the Application</h4><p>To register an application:</p><ol><li>Open the <a href="https://portal.azure.com/">Azure Portal</a> in a web browser and log in.</li><li>Go to Application Registrations and create a new application registration for the sample. Set the platform to <strong>Web</strong> and specify http://localhost:8080/.auth/login/aad/callback as the redirect URI.</li><li>From the <strong>Overview</strong> page for the new application registration, record the <strong>Application (client) ID</strong> and <strong>Directory (tenant) ID</strong> values. We will need those later.</li><li>Navigate to the <strong>Certificates &amp; secrets</strong> tab on the left sidebar and create a new client secret. Save the secret value because we will need that in a moment.</li></ol><p>Next, switch to a terminal. If you have never used Azure CLI on your machine, you will first need to log into Azure. Run:</p><pre>az login</pre><p>Follow the instructions in your browser to log into your Azure account. Once you are logged in, run:</p><pre>az ad app update \ <br>    --id {application/client ID} \<br>    --enable-id-token-issuance true</pre><h4>Adding Entra ID Authentication to the AppHost</h4><p>Go back to apphost.mts and add this code:</p><pre>const tenantId = builder.addParameter(&quot;entra-tenant-id&quot;); <br>const clientId = builder.addParameter(&quot;entra-client-id&quot;); <br>const clientSecret = builder.addParameter(&quot;entra-client-secret&quot;, { secret: true }); <br><br>await builder <br>    .addEasyAuthSimulator(&quot;web-auth&quot;, { port: 8080, authenticationRequired: true }) <br>    .withUpstream(web)<br>    .withEntraId(tenantId, clientId, clientSecret) <br>    .withExternalHttpEndpoints();</pre><p>This code adds three runtime parameters that are managed by Aspire and provided to Easy Auth Simulator through environment variables at runtime. You will store the values that you captured in the application registration section to connect Easy Auth Simulator to Entra ID.</p><h4>Testing Entra ID Authentication</h4><p>At this point, you are ready to go. In the terminal, run:</p><pre>aspire run</pre><p>This will start the AppHost. You will see a hyperlink to the dashboard. Click on the hyperlink to open the dashboard in a web browser.</p><p>When you open the Dashboard, at the top of the screen you should see an alert that you need to enter parameter values for the solution to start. Click on the button to set the values. In the form that appears, enter the values for the entra-tenant-id, entra-client-id, and entra-client-secret parameters. You can persist them to the secret store so that they will persist between runs. Once you set the parameters, the entire solution should start.</p><p>Open a web browser to <a href="http://localhost:8080/">http://localhost:8080</a>. You will be redirected to Entra ID and will need to log in using a Microsoft account. Once you log in and approve the requested permissions, you will be redirected back to `http://localhost:8080` and you should see your web application. To ensure that you are logged in, try browsing to <a href="http://localhost:8080/.auth/me">http://localhost:8080/.auth/me</a> in your the same web browser. This should return a JSON object containing the tokens and other information returned by Entra ID to the Easy Auth Simulator.</p><p>Browse to <a href="http://localhost:8080/.auth/logout">http://localhost:8080/.auth/logout</a> and terminate the AppHost before continuing with the next section.</p><h3>Authenticating with OpenID Connect</h3><p>You can also authenticate against a custom OpenID Connect provider. In this demonstration, we will use a publicly accessible demo service to illustrate setting this up. Edit apphost.mts and change the code to look like this:</p><pre>await builder <br>    .addEasyAuthSimulator(&#39;web-auth&#39;, { port: 8080, authenticationRequired: true }) <br>    .withUpstream(web) <br>    .withCustomOpenIdConnect( <br>        &quot;demo&quot;, <br>        &quot;https://demo.duendesoftware.com&quot;, <br>        builder.addParameter(&quot;demo-client-id&quot;), <br>        builder.addParameter(&quot;demo-client-secret&quot;, { secret: true }), <br>    ) <br>    .withExternalHttpEndpoints();</pre><p>Restart the Aspire server using aspire run and open the Aspire Dashboard again. You will again be prompted to enter values for the two new parameters. Set them equal to these values:</p><ul><li>demo-client-id: interactive.confidential</li><li>demo-client-secret: secret</li></ul><p>Save those parameters. When the web-auth service is running, open <a href="http://localhost:8080/">http://localhost:8080</a> in a web browser. You should immediately be redirected to the demo OpenID Connect service and asked to log in. Enter alice/ alice for the username and password and log in. You will be redirected back to the web application. Browsing to <a href="http://localhost:8080/.auth/me">http://localhost:8080/.auth/me</a> will show you the credential set that was collected from the demo OpenID Connect service.</p><h3>Working with Easy Auth Simulator</h3><p>Easy Auth Simulator works just like Easy Auth now and you can move forward with your application development. The web client can fetch the <a href="http://localhost:8080/.auth/me%60">http://localhost:8080/.auth/me</a> endpoint to obtain information about the user. Server code will receive the user information as HTTP headers:</p><ul><li>X-MS-CLIENT-PRINCIPAL-NAME</li><li>X-MS-CLIENT-PRINCIPAL-ID</li><li>X-MS-TOKEN-AAD-ACCESS-TOKEN: the JWT returned by Entra ID for calling APIs</li><li>X-MS-TOKEN-AAD-ID-TOKEN: the JWT containing identity information from Entra ID</li><li>X-MS-TOKEN-DEMO-ACCESS-TOKEN: The JWT returned by the demo OIDC service</li><li>X-MS-TOKEN-DEMO-ID-TOKEN: The identity JWT returned by the OIDC service</li></ul><p>For more information on how to use the headers, see the <a href="https://learn.microsoft.com/en-us/azure/container-apps/authentication">Authentication service documentation</a>.</p><h3>Conclusion</h3><p>Easy Auth Simulator is meant to help you build great Azure applications, and now you can use the built-in authentication features to build and debug your service locally. Even if you are not using Aspire, you can still download and run Easy Auth Service as a Docker container image and orchestrate it yourself with your own solution. For example, you can use it with Docker Compose if you are using that instead of Aspire.</p><p>I will be adding support for other identity providers in the coming weeks and will be adding things like OpenTelemetry support and more logging for better integration into the Aspire Dashboard. I welcome you to try this out on your own solutions and send me any feedback. Bugs can be reported on the repository’s <a href="https://github/mfcollins3/easyauthsimulator/issues">Issues</a> page and questions and new ideas are welcome on the <a href="https://github.com/mfcollins3/easyauthsimulator/discussions">Discussions</a> page.</p><p>Eventually the goal is to submit this into the official integrations feed for Aspire. It’s not ready for that yet, but hopefully soon it will be. In the meantime, I hope that you find it valuable for your own development projects.</p><p>GitHub: <a href="https://github.com/mfcollins3/easyauthsimulator">https://github.com/mfcollins3/easyauthsimulator</a></p><p><em>Originally published at </em><a href="https://michaelfcollins3.dev/posts/introducing-easy-auth-simulator"><em>https://michaelfcollins3.dev</em></a><em> on September 20, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb51eea67deb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Platform Container Images with GitHub Actions]]></title>
            <link>https://medium.com/neudesic-innovation/building-multi-platform-container-images-with-github-actions-e495f9441ad3?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e495f9441ad3</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 07:00:10 GMT</pubDate>
            <atom:updated>2025-03-17T18:11:29.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*95WafQ51DmN_lpJr.jpg" /></figure><p>While working on a different blog post, I ran into a scenario where I needed to produce a Docker container of a microservice that I was creating. This made me remember that my production architecture is different from my development architecture and I needed to produce a Docker container image that supported both architectures. In this post, I share with you how I ended up getting this to work in my GitHub Actions pipeline and publishing to the GitHub Package Registry.</p><p>Things were really nice for a few years. Apple had given up the Power PC platform and had migrated to Intel x64 chips and for a while everybody was on the same architecture. But then in 2020, Apple introduced their M1 chip which threw things back into a tizzy. Apple’s M1 chip adopted the <a href="https://en.wikipedia.org/wiki/ARM_architecture_family">ARM architecture</a> for their Mac computer line and began the migration away from Intel. Since then, ARM has been growing as there’s now a Microsoft Windows version that runs on ARM and Linux runs on ARM.</p><p>For software developers, the adoption of ARM has complicated how we package and deliver software. Whereas before we could assume for a few years that our software would always be deployed to x64 architecture, now we cannot make that assumption. Some users or production environments are running Intel. Other users and environments are ARM. If you don’t release your software so that it can run on both, some users may not be able to run your software. For others, they may be able to run it using an emulator such as <a href="https://en.wikipedia.org/wiki/Rosetta_(software)">Rosetta</a>, but performance could suffer.</p><p>Earlier today, I was writing a microservice for another blog post when I got inspired to package it in a Docker container. It was at that moment when it occurred to me that architecture mattered. I was building and testing the Docker container on my MacBook Pro M3, but then I automated the build process using GitHub Actions and I realized that GitHub Actions was building the Docker container for x64. This was going to be a problem if I wanted to pull down the Docker container and test it locally. That realization led me down the rabbit hole of discovering how to build a multi-platform Docker container, and do it with GitHub Actions.</p><h3>The Goal</h3><p>The objective of this post is that I need to build a docker container containing a Go microservice that I am creating. For production use, I want the footprint of the Docker container to be as small as possible, so I am basing the container on the <a href="https://www.alpinelinux.org/">Alpine Linux</a> operating system. Alpine Linux is a slimmed down version of Linux that even lacks a shell. It’s perfect for a Docker container because it just needs to be able to run your program.</p><p>The microservice that I am building is written in <a href="https://go.dev/">Go</a>. Go compiles programs into a single executable. For deployment into the Docker container, I only need to build the executable and copy it into the location in the container’s file system where I want to host it. Then I can configure the Docker container to run my microservice.</p><h3>Building the Microservice</h3><p>The first step is to figure out how I am going to build my microservice to support both Intel and ARM architectures. Fortunately, in this circumstance, the Go compiler can perform cross-compiling. At build time, I can specify the target operating system (Linux) and target architecture (Intel or ARM), and the Go compiler will produce an executable that will run on that platform. This is handled by specifying environment variables when running the go build command.</p><p>There is a problem though when building for Alpine Linux. Most Linux distributions use the libc library when they compile C code. When building a Go application, the Go compiler will, by default, link against libc and make it required when the program is loaded. Unfortunately, Alpine Linux does not use libc, but there’s a workaround. We can turn off CGo, and by extension, remove the dependency on the libc library so that we can build the program on a different version of Linux, but get it to run on Alpine Linux. This can be done byp assing the CGO_ENABLED environment variable to the go build command setting its value to 0. I haven&#39;t been able to find a better solution for this, so this is what I am doing.</p><p>On <a href="https://hub.docker.com/_/golang">Docker Hub</a>, there is a Go base container image that is based on Alpine Linux and includes the development tools to produce Alpine Linux executables with CGo enabled. I could implement a multi-stage Docker container that builds in the Go Alpine container and then copies the executable to an Alpine base container image. But by not doing that, I can speed up my build process by caching dependencies using GitHub Actions. I’ll save that for later in case I run into problems with this approach.</p><p>So I can perform cross compiling using the Go compiler by specifying three environment variables:</p><ul><li>CGO_ENABLED=0: this disabled CGo so that I can build executables that will run on Alpine Linux.</li><li>GOOS=linux: GOOS specifies the target operating system to build for. In this case, my target is always going to be Linux.</li><li>GOARCH=(amd64|arm64): GOARCH specifies the target architecture and for my needs will be either arm64 or amd64. There are other architectures that I can build for, but these will be my primary focus. amd64 will produce an executable that will run on Intel architectures. arm64 will produce an executable that will work on ARM architectures like Raspberry Pi or Apple Silicon.</li></ul><p>My Go build command will look like this:</p><pre>CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -v ./cmd/authorization</pre><p>This command will build a program whose main.go file is in the cmd/authorization subdirectory of the current directory. This command will produce an executable that will run on ARM architecture. I can switch it to amd64 to build for Intel architecture.</p><h3>Defining the Container</h3><p>The Dockerfile is pretty simple. Because I am going to cross-compile the program outside of the container to improve performance of the GitHub Actions workflow via caching, I&#39;m not going to mess with a multi-stage build. I&#39;m simply going to use an Alpine Linux base container and then copy my program into the file system:</p><pre>FROM alpine:3.21.3<br><br>WORKDIR /opt/authorization<br><br>COPY build/authorization bin/<br><br>EXPOSE 80<br>ENTRYPOINT [&quot;bin/authorization&quot;]<br>CMD [&quot;server&quot;]</pre><p>I am storing my program in the /opt/authorization folder. Following the typical convention, I&#39;m putting the executable in the /opt/authorization/bin subdirectory. I may in the future have additional resources or configuration files, so I&#39;m kind of planning ahead a little. Because Alpine Linux does not include a shell, I&#39;m setting my executable as the default executable using the ENTRYPOINT directive and setting the default execution mode to run my program in server mode. I know I haven&#39;t shown the actual program that I&#39;m building yet, but I will in a future post.</p><h3>Building the Platform-Specific Containers</h3><p>Now that I’m able to cross-compile my program and then build a Docker container, it’s time to automate this using GitHub Actions. I’m not an expert on these multi-platform containers, but what I believe is happening is that I’m producing two container images that each target a specific platform. Then I’m creating a third container image that references the platform-specific containers. At runtime, Docker will pull the third container image, use the metadata inside of it to match the host platform, and then will download the correct platform-specific image. So the build process mirrors this:</p><ol><li>Build the platform-specific containers</li><li>Create the metadata container that references the platform-specific containers</li></ol><p>The first job in my GitHub Actions workflow uses the matrix capabilities of GitHub Actions to run the same job concurrently while varying the architectures. Since my target operating system is always going to be Linux, I just need to vary the architectures between amd64 and arm64:</p><pre>  build_and_test:<br>    name: Build and Test<br>    runs-on: ubuntu-24.04<br>    strategy:<br>      fail-fast: false<br>      matrix:<br>        architecture:<br>          - amd64<br>          - arm64<br>    steps:</pre><p>The first step is obviously going to be to clone my repository and check out the branch that I’m building. The branch will either be the main branch or a pull request branch.</p><pre>      - name: Checkout the repository<br>        uses: actions/checkout@v4</pre><p>Next, I will install and activate the version of Go that I want to build with. I can use the <a href="https://github.com/actions/setup-go">setup-go</a> action to do this:</p><pre>      - name: Setup Go<br>        uses: actions/setup-go@v5<br>        with:<br>          go-version-file: &#39;src/authorization/go.mod&#39;<br>          cache-dependency-path: &#39;src/authorization/go.sum&#39;</pre><p>The setup-go action has a couple of very cool features. First, instead of having to hard code the version number for Go in my workflow, I can instead point setup-go to either a go.work file for a workspace or a go.mod file for a Go module and setup-go will extract the Go version number from there. That&#39;s nice, because I can keep the workflow generic. The other feature is the cache-dependency-path parameter. This is where the performance boost comes in because my program has a number of dependencies that have to be downloaded. setup-go will cache the dependencies after the build and will reload them from cache instead of downloading them again for each build, speeding the build. As long as the referenced go.sum file hasn&#39;t changed, the cached dependencies will be reloaded. If the go.sum file is updated with new or updated dependencies, the cache will be rebuilt.</p><p>I will next install the Docker Buildx tool that I will be using for building the Docker container and publishing it to GitHub Package Registry:</p><pre>      - name: Setup Docker Buildx<br>        uses: docker/setup-buildx-action@v3</pre><p>Now it is time to build the program that I am going to copy into the Docker container. This is going to use the cross-compiling environment variables that I discussed in the <a href="https://michaelfcollins3.dev/blog/2025/03/multiplatform-containers-with-github-actions/#building-the-container">building section</a>.</p><pre>      - name: Build Authorization Service<br>        run: go build -v -o build/ ./cmd/authorization<br>        working-directory: src/authorization<br>        env:<br>          GCO_ENABLED: 0<br>          GOOS: linux<br>          GOARCH: ${{ matrix.architecture }}</pre><p>Notice the GOARCH environment variable. Here I&#39;m referencing the matrix.architecture value. When the build runs, GitHub Actions will run this specific build job for each variant of the paraeters in the matrix section. Referencing matrix.architecture gives me the architecture variant for the current execution of the build job. For one job, matrix.architecture will be amd64. For the other job, it will be arm64.</p><p>Normally, my next step would be to run the automated unit test suite before going any further. But at the moment, my program is a simple shell program that just launches an HTTP server, so there’s nothing really ot test yet. I’ll add that in the future.</p><p>Now that the program is built, we’re going to start the process of building and publishing the Docker container to GitHub Package Registry. The first move is that we need to log into GitHub Package Registry’s Docker Hub endpoint. We can use a GitHub Action provided by Docker to do this:</p><pre>      - name: Log into GitHub Container Registry<br>        uses: docker/login-action@v3<br>        with:<br>          registry: ${{ env.REGISTRY}}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}</pre><p>The env.REGISTRY environment variable is defined as ghcr.io, which is the base URL for GitHub Package Registry. I&#39;ll show the full workflow at the end of the article. github.actor is the username of the user that triggered the GitHub Actions workflow. secrets.GITHUB_TOKEN is an access token that GitHub generated for the GitHub Action workflow to use to access the GitHub API and services. I customize the access token at the beginning of the workflow with additional permissions for publishing to GitHub Package Registry:</p><pre>permissions:<br>  contents: read<br>  packages: write<br>  attestations: write<br>  id-token: write</pre><p>After logging in successfully, there’s another Docker action that we’ll call to extract metadata from Git and GitHub for the repository being built. The docker/metadata-action action will generate tags and version numbers that will be used to label the Docker container that gets built. For example, if the GitHub Actions workflow is running for a pull request, docker/metadata-action will label the built Docker container with pr-4 indicating that the build is correlated with the pull request with id 4.</p><pre>      - name: Get Docker Metadata<br>        id: meta<br>        uses: docker/metadata-action@v5<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}</pre><p>With the metadata, we can now build the Docker container image. Docker provides the GitHub Action docker/build-push-action that uses Buildx to build the container image and then push it to a container registry (GitHub Package Registry). We&#39;ll pass it the metadata output by the docker/metadata-action action:</p><pre>      - name: Build Docker Container<br>        id: push<br>        uses: docker/build-push-action@v6<br>        with:<br>          context: src/authorization<br>          platforms: linux/${{ matrix.architecture }}<br>          labels: ${{ steps.meta.outputs.labels}}<br>          tags: ${{ steps.meta.outputs.tags }}<br>          push: true</pre><p>When Dockerx builds a container image, it will generate a cryptographic hash, called the digest, that is used to uniquely identify the container image. The digest is calculated from the data inside of the image, so if something changes in the image, the digest will no longer match. This digest uniquely identifies the platform image. When we build the multi-platform container image, we need to store the platform-specific image digest in the multi-platform container image so that Docker can find the matching container image for the runtime platform. Because we’re building each platform in their own job, we’re going to write the digest to a file and export it as a workflow artifact that we can use in the second job in the build process that runs after all of the platform images are created.</p><pre>      - name: Export digest<br>        run: |<br>          mkdir -p ${{ runner.temp }}/digests<br>          digest=&quot;${{ steps.push.outputs.digest }}&quot;<br>          touch &quot;${{ runner.temp }}/digests/${digest#sha256:}&quot;<br>      - name: Upload digest<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: digests-linux-${{ matrix.architecture }}<br>          path: ${{ runner.temp }}/digests/*<br>          if-no-files-found: error<br>          retention-days: 1</pre><p>At the end of this job, we will have produced platform-specific Docker container images for amd64 and arm64 running on Linux.</p><h3>Building the Multi-Platform Container Image</h3><p>We have our platform-specific container images. Now we need to generate the generic container image that references the platform-specific container images. We want consumers to reference the multi-platform container image so that they don’t need to worry about finding and keeping track of the platform-specific container images. At the end of the previous job, we generated and exported digests that uniquely identified our platform-specific containers, and then we uploaded these digests in text files as artifacts to the GitHub Actions workflow. We’re going to start by downloading these artifacts into the new job:</p><pre>      - name: Download Digests<br>        uses: actions/download-artifact@v4<br>        with:<br>          path: ${{ runner.temp }}/digests<br>          pattern: digests-*<br>          merge-multiple: true</pre><p>Because we’re running in a new job on a different build agent, we need to log into GitHub Package Registry again and set up Docker Buildx:</p><pre>      - name: Log into GitHub Container Registry<br>        uses: docker/login-action@v3<br>        with:<br>          registry: ${{ env.REGISTRY}}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br><br>      - name: Setup Docker Buildx<br>        uses: docker/setup-buildx-action@v3</pre><p>We next generate more metadata that will be used for the new multi-platform container image:</p><pre>      - name: Get Docker Metadata<br>        id: meta<br>        uses: docker/metadata-action@v5<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}<br>          tags: |<br>            type=ref,event=branch<br>            type=ref,event=pr<br>            type=semver,pattern={{version}}<br>            type=semver,pattern={{major}}.{{minor}}</pre><p>We then create the multi-platform container image that references our platform-specific container images and publish that to GitHub Package Registry:</p><pre>      - name: Create manifest list and push<br>        working-directory: ${{ runner.temp }}/digests<br>        run: |<br>          docker buildx imagetools create $(jq -cr &#39;.tags | map(&quot;-t &quot; + .) | join(&quot; &quot;)&#39; &lt;&lt;&lt; &quot;$DOCKER_METADATA_OUTPUT_JSON&quot;) \<br>            $(printf &#39;${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}@sha256:%s &#39; *)</pre><p>And, while not necessary, we can use the docker command to pull metadata from the GitHub Package Registry for our container and log it to the build output for reporting purposes so that we can inspect it later if there&#39;s any problems:</p><pre>     - name: Inspect Image<br>        run: |<br>          docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }}</pre><p>This is an example of the output generated by this step that shows the contents of the multi-platform container image:</p><pre>Run docker buildx imagetools inspect ghcr.io/mfcollins3/authorization-service:pr-3<br>  docker buildx imagetools inspect ghcr.io/mfcollins3/authorization-service:pr-3<br>  shell: /usr/bin/bash -e {0}<br>  env:<br>    REGISTRY: ghcr.io<br>    REGISTRY_IMAGE: mfcollins3/authorization-service<br>    DOCKER_METADATA_OUTPUT_VERSION: pr-3<br>    DOCKER_METADATA_OUTPUT_TAGS: ghcr.io/mfcollins3/authorization-service:pr-3<br>    DOCKER_METADATA_OUTPUT_LABELS: org.opencontainers.image.created=2025-03-16T05:05:28.871Z<br>  org.opencontainers.image.description=Authorization Service performs user identity management and application authorization services for websites and software products or cloud services using OAuth 2, OpenID Connect, and WebAuthn.<br>  org.opencontainers.image.licenses=NOASSERTION<br>  org.opencontainers.image.revision=7c1d75b32ba9f2b9162bd01f452fbbb508ab0634<br>  org.opencontainers.image.source=https://github.com/mfcollins3/authorization-service<br>  org.opencontainers.image.title=authorization-service<br>  org.opencontainers.image.url=https://github.com/mfcollins3/authorization-service<br>  org.opencontainers.image.version=pr-3<br>    DOCKER_METADATA_OUTPUT_ANNOTATIONS: manifest:org.opencontainers.image.created=2025-03-16T05:05:28.871Z<br>  manifest:org.opencontainers.image.description=Authorization Service performs user identity management and application authorization services for websites and software products or cloud services using OAuth 2, OpenID Connect, and WebAuthn.<br>  manifest:org.opencontainers.image.licenses=NOASSERTION<br>  manifest:org.opencontainers.image.revision=7c1d75b32ba9f2b9162bd01f452fbbb508ab0634<br>  manifest:org.opencontainers.image.source=https://github.com/mfcollins3/authorization-service<br>  manifest:org.opencontainers.image.title=authorization-service<br>  manifest:org.opencontainers.image.url=https://github.com/mfcollins3/authorization-service<br>  manifest:org.opencontainers.image.version=pr-3<br>    DOCKER_METADATA_OUTPUT_JSON: {&quot;tags&quot;:[&quot;ghcr.io/mfcollins3/authorization-service:pr-3&quot;],&quot;labels&quot;:{&quot;org.opencontainers.image.created&quot;:&quot;2025-03-16T05:05:28.871Z&quot;,&quot;org.opencontainers.image.description&quot;:&quot;Authorization Service performs user identity management and application authorization services for websites and software products or cloud services using OAuth 2, OpenID Connect, and WebAuthn.&quot;,&quot;org.opencontainers.image.licenses&quot;:&quot;NOASSERTION&quot;,&quot;org.opencontainers.image.revision&quot;:&quot;7c1d75b32ba9f2b9162bd01f452fbbb508ab0634&quot;,&quot;org.opencontainers.image.source&quot;:&quot;https://github.com/mfcollins3/authorization-service&quot;,&quot;org.opencontainers.image.title&quot;:&quot;authorization-service&quot;,&quot;org.opencontainers.image.url&quot;:&quot;https://github.com/mfcollins3/authorization-service&quot;,&quot;org.opencontainers.image.version&quot;:&quot;pr-3&quot;},&quot;annotations&quot;:[&quot;manifest:org.opencontainers.image.created=2025-03-16T05:05:28.871Z&quot;,&quot;manifest:org.opencontainers.image.description=Authorization Service performs user identity management and application authorization services for websites and software products or cloud services using OAuth 2, OpenID Connect, and WebAuthn.&quot;,&quot;manifest:org.opencontainers.image.licenses=NOASSERTION&quot;,&quot;manifest:org.opencontainers.image.revision=7c1d75b32ba9f2b9162bd01f452fbbb508ab0634&quot;,&quot;manifest:org.opencontainers.image.source=https://github.com/mfcollins3/authorization-service&quot;,&quot;manifest:org.opencontainers.image.title=authorization-service&quot;,&quot;manifest:org.opencontainers.image.url=https://github.com/mfcollins3/authorization-service&quot;,&quot;manifest:org.opencontainers.image.version=pr-3&quot;]}<br>    DOCKER_METADATA_OUTPUT_BAKE_FILE_TAGS: /home/runner/work/_temp/docker-actions-toolkit-zNgsMq/docker-metadata-action-bake-tags.json<br>    DOCKER_METADATA_OUTPUT_BAKE_FILE_LABELS: /home/runner/work/_temp/docker-actions-toolkit-zNgsMq/docker-metadata-action-bake-labels.json<br>    DOCKER_METADATA_OUTPUT_BAKE_FILE_ANNOTATIONS: /home/runner/work/_temp/docker-actions-toolkit-zNgsMq/docker-metadata-action-bake-annotations.json<br>    DOCKER_METADATA_OUTPUT_BAKE_FILE: /home/runner/work/_temp/docker-actions-toolkit-zNgsMq/docker-metadata-action-bake.json<br>Name:      ghcr.io/mfcollins3/authorization-service:pr-3<br>MediaType: application/vnd.oci.image.index.v1+json<br>Digest:    sha256:b67ea466fc42eae57f3c17c9b124343f34b89562b7d34ba83ed7906aa4a72784<br>           <br>Manifests: <br>  Name:        ghcr.io/mfcollins3/authorization-service:pr-3@sha256:554e913f6d2dee77c999fbf3b5ce60ed271078fe66814e4faa31b5284c89a705<br>  MediaType:   application/vnd.oci.image.manifest.v1+json<br>  Platform:    linux/arm64<br>               <br>  Name:        ghcr.io/mfcollins3/authorization-service:pr-3@sha256:579f330480e0e9925171db67ecb24247ec268a90db7a63b70644f0eb9b694745<br>  MediaType:   application/vnd.oci.image.manifest.v1+json<br>  Platform:    unknown/unknown<br>  Annotations: <br>    vnd.docker.reference.digest: sha256:554e913f6d2dee77c999fbf3b5ce60ed271078fe66814e4faa31b5284c89a705<br>    vnd.docker.reference.type:   attestation-manifest<br>               <br>  Name:        ghcr.io/mfcollins3/authorization-service:pr-3@sha256:e215d4e9ca82cd5091f99999c0e09f1dc091355af0c124c5275028f9b54560d6<br>  MediaType:   application/vnd.oci.image.manifest.v1+json<br>  Platform:    linux/amd64<br>               <br>  Name:        ghcr.io/mfcollins3/authorization-service:pr-3@sha256:eb543a1d0066cd0bcf9994448105e0df14fc7634a9c46e9c50ed6ddececc6199<br>  MediaType:   application/vnd.oci.image.manifest.v1+json<br>  Platform:    unknown/unknown<br>  Annotations: <br>    vnd.docker.reference.digest: sha256:e215d4e9ca82cd5091f99999c0e09f1dc091355af0c124c5275028f9b54560d6<br>    vnd.docker.reference.type:   attestation-manifest</pre><p>And that’s it! We’re done!</p><h3>What Did We Do?</h3><p>To summarize what we did in this post:</p><ol><li>We built a program using cross-compilation that will run in Apline Linux on either Intel/AMD x64 architecture or ARM architecture (Raspberry Pi, Apple Silicon, other ARM-based computers).</li><li>We created Docker container images based on Alpine Linux for the target architecture and copied the program into the container for execution.</li><li>We created a multi-platform Docker container image that references the platform-specific container images.</li><li>We published the multi-platform container image and the platform-specific container images to GitHub Package Registry.</li></ol><p>The end result now is that a consumer, if they wanted to download and run my Docker container, can run:</p><pre>docker pull ghcr.io/mfcollins3/authorization-service</pre><p>and they will get the Docker container that matches the machine architecture that they are running on.</p><h3>For More Information…</h3><p>In writing this article, I relied heavily on documentation and examples in the Docker documentation. I took the examples here and modified them to work with GitHub Package Registry instead of using <a href="https://hub.docker.com/">Docker Hub</a>.</p><ul><li><a href="https://docs.docker.com/build/building/multi-platform/">Multi-platform builds</a>: This document describes the concepts around multi-platform builds in more detail and their importance. It also has a section on strategies for implementing multi-platform builds.</li><li><a href="https://docs.docker.com/build/ci/github-actions/multi-platform/#distribute-build-across-multiple-runners">Multi-platform image with GitHub Actions</a>: Shows example GitHub Actions workflows for creating multi-platform images.</li></ul><h3>The Complete Source Code</h3><p>Here is the complete GitHub Actions workflow that I ended up with:</p><pre># authorization_service.yaml<br>#<br># This GitHub Actions workflow will build and package Authorization Service<br># for deployment using Docker.<br><br>name: Authorization Service<br><br>on:<br>  push:<br>    branches:<br>      - main<br>    paths:<br>      - &#39;.github/workflows/authorization_service.yaml&#39;<br>      - &#39;src/authorization/**&#39;<br>  pull_request:<br>    branches:<br>      - main<br>    paths:<br>      - &#39;.github/workflows/authorization_service.yaml&#39;<br>      - &#39;src/authorization/**&#39;<br><br>env:<br>  REGISTRY: ghcr.io<br>  REGISTRY_IMAGE: ${{ github.repository_owner }}/authorization-service<br><br>permissions:<br>  contents: read<br>  packages: write<br>  attestations: write<br>  id-token: write<br><br>jobs:<br>  build_and_test:<br>    name: Build and Test<br>    runs-on: ubuntu-24.04<br>    strategy:<br>      fail-fast: false<br>      matrix:<br>        architecture:<br>          - amd64<br>          - arm64<br>    steps:<br>      - name: Checkout the repository<br>        uses: actions/checkout@v4<br>      - name: Setup Go<br>        uses: actions/setup-go@v5<br>        with:<br>          go-version-file: &#39;src/authorization/go.mod&#39;<br>          cache-dependency-path: &#39;src/authorization/go.sum&#39;<br>      - name: Setup Docker Buildx<br>        uses: docker/setup-buildx-action@v3<br>      - name: Build Authorization Service<br>        run: go build -v -o build/ ./cmd/authorization<br>        working-directory: src/authorization<br>        env:<br>          GCO_ENABLED: 0<br>          GOOS: linux<br>          GOARCH: ${{ matrix.architecture }}<br>      - name: Log into GitHub Container Registry<br>        uses: docker/login-action@v3<br>        with:<br>          registry: ${{ env.REGISTRY}}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br>      - name: Get Docker Metadata<br>        id: meta<br>        uses: docker/metadata-action@v5<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}<br>      - name: Build Docker Container<br>        id: push<br>        uses: docker/build-push-action@v6<br>        with:<br>          context: src/authorization<br>          platforms: linux/${{ matrix.architecture }}<br>          labels: ${{ steps.meta.outputs.labels}}<br>          tags: ${{ steps.meta.outputs.tags }}<br>          push: true<br>      - name: Generate Artifact Attestation<br>        uses: actions/attest-build-provenance@v2<br>        with:<br>          subject-name: ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}<br>          subject-digest: ${{ steps.push.outputs.digest }}<br>          push-to-registry: true<br>      - name: Export digest<br>        run: |<br>          mkdir -p ${{ runner.temp }}/digests<br>          digest=&quot;${{ steps.push.outputs.digest }}&quot;<br>          touch &quot;${{ runner.temp }}/digests/${digest#sha256:}&quot;<br>      - name: Upload digest<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: digests-linux-${{ matrix.architecture }}<br>          path: ${{ runner.temp }}/digests/*<br>          if-no-files-found: error<br>          retention-days: 1<br><br>  merge_platform_containers:<br>    name: Merge Platform Containers<br>    runs-on: ubuntu-24.04<br>    needs: build_and_test<br>    steps:<br>      - name: Download Digests<br>        uses: actions/download-artifact@v4<br>        with:<br>          path: ${{ runner.temp }}/digests<br>          pattern: digests-*<br>          merge-multiple: true<br>      - name: Log into GitHub Container Registry<br>        uses: docker/login-action@v3<br>        with:<br>          registry: ${{ env.REGISTRY}}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br>      - name: Setup Docker Buildx<br>        uses: docker/setup-buildx-action@v3<br>      - name: Get Docker Metadata<br>        id: meta<br>        uses: docker/metadata-action@v5<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}<br>          tags: |<br>            type=ref,event=branch<br>            type=ref,event=pr<br>            type=semver,pattern={{version}}<br>            type=semver,pattern={{major}}.{{minor}}<br>      - name: Create manifest list and push<br>        working-directory: ${{ runner.temp }}/digests<br>        run: |<br>          docker buildx imagetools create $(jq -cr &#39;.tags | map(&quot;-t &quot; + .) | join(&quot; &quot;)&#39; &lt;&lt;&lt; &quot;$DOCKER_METADATA_OUTPUT_JSON&quot;) \<br>            $(printf &#39;${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}@sha256:%s &#39; *)<br>      - name: Inspect Image<br>        run: |<br>          docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }}</pre><p><em>Originally published at </em><a href="https://michaelfcollins3.dev/blog/2025/03/multiplatform-containers-with-github-actions/"><em>https://michaelfcollins3.dev</em></a><em> on March 17, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e495f9441ad3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/building-multi-platform-container-images-with-github-actions-e495f9441ad3">Building Multi-Platform Container Images with GitHub Actions</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A GitHub Action for Importing Blue Sky RSS Feeds]]></title>
            <link>https://medium.com/neudesic-innovation/a-github-action-for-importing-blue-sky-rss-feeds-a31fc20a4f8c?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a31fc20a4f8c</guid>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[blue-sky]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 07:00:14 GMT</pubDate>
            <atom:updated>2025-03-12T15:40:07.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNBzKXi24WrIXi_M.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tim Mossholder</a> on <a href="https://unsplash.com/photos/cogs-and-gears-GmvH5v9l3K4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>When building my <a href="https://michaelfcollins3.dev/">new personal website and blog</a>, I wanted to bring in my most recent Blue Sky posts to also attract new readers to follow me on Blue Sky. I ran into an interesting problem though. My website generator couldn’t read timestamps in the format that BlueSky published them. In this article, I walk through what I want to do, the problem that I hit, and my first exploration into building a custom GitHub Action to solve the problem and get my Blue Sky posts on my website.</p><h3>The Problem</h3><p>My website is a static website, meaning that there is no application behind it. When I publish my website, it’s just a set of HTML files, CSS, a little JavaScript, and images and other assets. The files are served from an HTTP server. I’m hosting my website using <a href="https://pages.github.com/">GitHub Pages</a>, so I am assuming that there’s some sort of content delivery network with edge locations around the world where my website is cached and served from.</p><p>I generate my website using <a href="https://gohugo.io/">Hugo</a>. Hugo is a static website generator written in Go that has a lot of great features for content management and templating. And Hugo is very fast when generating static websites.</p><p>One feature that I wanted in my new website was the ability to have a section on the homepage where I could show posts that I am making to <a href="https://bluesky.app/">Blue Sky</a>. Blue Sky is my new microblogging site. And if you’re interested in following me on Blue Sky, check out <a href="https://bsky.app/profile/mfcollins3.bsky.social">my profile</a>.</p><p>Hugo has the ability to load external data and use that data to generate HTML content. And Blue Sky has the ability to generate RSS feeds containing user posts. I ran into a problem though in that Hugo has limitations on the format that it supports for timestamps in data and Blue Sky doesn’t output the RSS &lt;pubDate&gt; field in a format that Hugo supports. So to add my Blue Sky posts to my website, I had to go a different route.</p><p>For example, here is a sample of the RSS feed from my Blue Sky profile as of when I wrote this article:</p><pre>&lt;rss version=&quot;2.0&quot;&gt;<br>    &lt;channel&gt;<br>        &lt;description&gt;I am a professional software developer and I love to cook. I work for Neudesic and am a Senior Director for Application Innovation in the Desert market (Phoenix and Las Vegas). I am currently based in the Phoenix metro area and live in Surprise, Arizona.&lt;/description&gt;<br>        &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social&lt;/link&gt;<br>        &lt;title&gt;@mfcollins3.bsky.social - Michael F. Collins, III&lt;/title&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3lk5r4x75cs2t&lt;/link&gt;<br>            &lt;description&gt;I&#39;ve been listening to the audiobook of The City of Mirrors again on Audible. I desperately need movies done of this book trilogy. It&#39;s so unfortunate that Fox messed up The Passage and the series was cancelled after the first season. I just want to see &quot;the seige&quot; happen on the big screen.&lt;/description&gt;<br>            &lt;pubDate&gt;12 Mar 2025 04:38 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3lk5r4x75cs2t&lt;/guid&gt;<br>        &lt;/item&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3lk5qiymcbk2t&lt;/link&gt;<br>            &lt;description&gt;Just published: a new article about fair-code and software licensing. This is a look at how I might be able to start building products openly, sharing the source code for others to see, while protecting rights to earn income from my software products: https://michaelfcollins3.dev/blog/2025/03/fair-use-licensing/&lt;/description&gt;<br>            &lt;pubDate&gt;12 Mar 2025 04:27 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3lk5qiymcbk2t&lt;/guid&gt;<br>        &lt;/item&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3ljyssrxgms2l&lt;/link&gt;<br>            &lt;description&gt;2025 has been a year of setting and achieving goals, no matter how difficult they are. So far I&#39;ve attacked my caffeine addition and have been &quot;sober&quot; for over 60 days now. I&#39;m back in the gym and working to rebuild me. I&#39;m also setting aside an hour each day for &quot;me&quot; time to read and learn.&lt;/description&gt;<br>            &lt;pubDate&gt;10 Mar 2025 05:24 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3ljyssrxgms2l&lt;/guid&gt;<br>        &lt;/item&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3ljysgjilss2l&lt;/link&gt;<br>            &lt;description&gt;After a long hiatus, I&#39;m back with a new website and blog trying to share my thoughts and ideas around software development. Here&#39;s my first post reintroducing development containers and what you can do with them: https://michaelfcollins3.dev/blog/2025/03/development-containers/&lt;/description&gt;<br>            &lt;pubDate&gt;10 Mar 2025 05:18 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3ljysgjilss2l&lt;/guid&gt;<br>        &lt;/item&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3lcrjwpsahk2t&lt;/link&gt;<br>            &lt;description&gt;You know when you spend all day building something great and everything is clicking, but your program isn’t working right and you’re getting frustrated and then you take a break to go to dinner and come home and read the documentation and then you change your code to do it the right way?&lt;/description&gt;<br>            &lt;pubDate&gt;08 Dec 2024 06:01 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3lcrjwpsahk2t&lt;/guid&gt;<br>        &lt;/item&gt;<br>        &lt;item&gt;<br>            &lt;link&gt;https://bsky.app/profile/mfcollins3.bsky.social/post/3lbocp57wks2e&lt;/link&gt;<br>            &lt;description&gt;I built my biggest dev container to date: Prometheus, Grafana, Dapr services, Redis, RabbitMQ, Azurite, SQL Server, Cosmos DB emulator, OpenZipkin, APISIX, Traefik, and ngrok. It’s almost the ultimate dev container for local Azure development!&lt;/description&gt;<br>            &lt;pubDate&gt;24 Nov 2024 05:48 +0000&lt;/pubDate&gt;<br>            &lt;guid isPermaLink=&quot;false&quot;&gt;at://did:plc:ukyfcg7nrk44w2wqpj2afjl5/app.bsky.feed.post/3lbocp57wks2e&lt;/guid&gt;<br>        &lt;/item&gt;<br>    &lt;/channel&gt;<br>&lt;/rss&gt;</pre><p>Blue Sky outputs the &lt;pubDate&gt; element with a timestamp in the format 24 Nov 2024 05:48 +0000. The issue is that Hugo doesn&#39;t recognize that format even though it&#39;s valid. Hugo needs the seconds in the timestamp and won&#39;t accept it without. I could attempt to create an issue in Hugo&#39;s GitHub repository or fix it myself, but that would take time and may or may not get approved. Or I could look to fix it some other way on my own to rewrite the timestamp so that Hugo will be able to parse the RSS feed.</p><p>I use <a href="https://github.com/features/actions">GitHub Actions</a> to build and publish my website to GitHub Pages. Using GitHub Actions, I had two options:</p><ol><li>Figure out how to use a shell script or call a small custom program that could import the RSS feed from Blue Sky and rewrite it for Hugo,</li><li>Create a reusable GitHub Action that I and others can use to import the RSS feed from Blue Sky and rewrite it for Hugo.</li></ol><p>I had limited experience in writing custom GitHub Actions, but this sounded like a great opportunity to get in there and do it, so I chose #2. The rest of this post explains how I built my custom GitHub Action and what I learned along the way.</p><h3>The Solution</h3><p>A custom GitHub Action begins with a file named action.yaml. This file is stored in the root directory of the GitHub repository containing the custom action. action.yaml contains metadata about the GitHub Action including a list of inputs that are sent to the GitHub Action at runtime, outputs produced by the GitHub Action, and information on how to run the GitHub Action. GitHub Actions can be written either using JavaScript or as a Docker container. At the time, I didn&#39;t want to spend the time figuring out how to do this in JavaScript, so I opted to write my custom action in Go and deploy it as a Docker container instead.</p><p>Here’s my <a href="https://github.com/mfcollins3/hugoify-bluesky-rss-feed/blob/main/action.yaml">action.yaml</a> file:</p><pre>name: Hugoify Blue Sky RSS Feed<br>author: Michael F. Collins, III<br>description: Downloads an RSS feed from Blue Sky and formats the RSS for Hugo to use.<br>inputs:<br>  url:<br>    description: The URL of the Blue Sky RSS feed to download.<br>    required: true<br>  path:<br>    description: The path to save the re-formatted RSS feed.<br>    required: true<br>runs:<br>  using: docker<br>  image: Dockerfile</pre><p>My custom GitHub Action will has two inputs:</p><ul><li>url: the URL for where the RSS feed can be found and downloaded from.</li><li>path: the output path where the patched RSS feed will be written to.</li></ul><p>In my GitHub Actions workflow, I can specify these values:</p><pre>- name: Download and Format the Blue Sky RSS Feed<br>  uses: mfcollins3/hugoify-bluesky-rss-feed@main<br>  with:<br>    url: https://bsky.app/profile/mfcollins3.bsky.social/rss<br>    path: content/bluesky_rss.xml</pre><p>When my GitHub Action is executed, the parameters are passed to my action using environment variables with an INPUT_ prefix:</p><ul><li>INPUT_URL</li><li>INPUT_PATH</li></ul><p>The first thing that I did in Go was to model the RSS feed structure for parsing and generating the RSS XML:</p><pre>type rss struct {<br> XMLName xml.Name `xml:&quot;rss&quot;`<br> Version string   `xml:&quot;version,attr&quot;`<br> Channel channel  `xml:&quot;channel&quot;`<br>}<br><br>type channel struct {<br> Description string `xml:&quot;description&quot;`<br> Link        string `xml:&quot;link&quot;`<br> Title       string `xml:&quot;title&quot;`<br> Items       []item `xml:&quot;item&quot;`<br>}<br><br>type item struct {<br> Link        string `xml:&quot;link&quot;`<br> Description string `xml:&quot;description&quot;`<br> PubDate     string `xml:&quot;pubDate&quot;`<br> Guid        guid   `xml:&quot;guid&quot;`<br>}<br><br>type guid struct {<br> IsPermaLink string `xml:&quot;isPermaLink,attr&quot;`<br> Value       string `xml:&quot;,chardata&quot;`<br>}</pre><p>Next, I read the environment variables to get the download URL and the output path:</p><pre>url, ok := os.LookupEnv(&quot;INPUT_URL&quot;)<br>if !ok {<br>    log.Fatal(&quot;The url input is required.&quot;)<br>}<br><br>path, ok := os.LookupEnv(&quot;INPUT_PATH&quot;)<br>if !ok {<br>    log.Fatal(&quot;The path input is required.&quot;)<br>}</pre><p>Next, I downloaded the RSS feed from Blue Sky and parsed the RSS XML document:</p><pre>resp, err := http.Get(url)<br>if err != nil {<br>    log.Fatalf(&quot;Failed to download the RSS feed: %v&quot;, err)<br>}<br><br>defer func() {<br>    _ = resp.Body.Close()<br>}()<br><br>if resp.StatusCode != http.StatusOK {<br>    log.Fatalf(<br>        &quot;Failed to download RSS feed. Status code: %d&quot;,<br>        resp.StatusCode,<br>    )<br>}<br><br>var rss rss<br>decoder := xml.NewDecoder(resp.Body)<br>if err = decoder.Decode(&amp;rss); err != nil {<br>    log.Fatalf(&quot;Failed to parse the RSS feed: %v&quot;, err)<br>}</pre><p>Now that I had the RSS feed data, I can loop through the feed items to parse and patch the &lt;pubDate&gt; timestamp with a format that Hugo will understand:</p><pre>for i := range rss.Channel.Items {<br>    pubDate, err := time.Parse(<br>        &quot;02 Jan 2006 15:04 -0700&quot;,<br>        rss.Channel.Items[i].PubDate,<br>    )<br>    if err != nil {<br>        log.Fatalf(&quot;Failed to parse the pubDate field: %v&quot;, err)<br>    }<br><br>    rss.Channel.Items[i].PubDate = pubDate.Format(<br>        &quot;2006-01-02T15:04:05-07:00&quot;,<br>    )<br>}</pre><p>Line 2 uses the time.Parse function to parse the timestamp generated by Blue Sky which is in the format 02 Jan 2006 15:04 -0700. I&#39;m reformatting the timestamp on line 10 using a standard Internet format that Hugo does support in the format yyyy-mm-ddThh:mm:ss&lt;time offset&gt;.</p><p>Finally, I’m writing the patched RSS feed back out as XML:</p><pre>file, err := os.Create(path)<br>if err != nil {<br>    log.Fatalf(&quot;Failed to create the file: %v&quot;, err)<br>}<br><br>defer func() {<br>    _ = file.Close()<br>}()<br><br>encoder := xml.NewEncoder(file)<br>encoder.Indent(&quot;&quot;, &quot;  &quot;)<br>if err = encoder.Encode(rss); err != nil {<br>    log.Fatalf(&quot;Failed to write the RSS feed: %v&quot;, err)<br>}</pre><p>Here’s the entire source code for my custom GitHub Action:</p><pre>package main<br><br>import (<br> &quot;encoding/xml&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br>)<br><br>type rss struct {<br> XMLName xml.Name `xml:&quot;rss&quot;`<br> Version string   `xml:&quot;version,attr&quot;`<br> Channel channel  `xml:&quot;channel&quot;`<br>}<br><br>type channel struct {<br> Description string `xml:&quot;description&quot;`<br> Link        string `xml:&quot;link&quot;`<br> Title       string `xml:&quot;title&quot;`<br> Items       []item `xml:&quot;item&quot;`<br>}<br><br>type item struct {<br> Link        string `xml:&quot;link&quot;`<br> Description string `xml:&quot;description&quot;`<br> PubDate     string `xml:&quot;pubDate&quot;`<br> Guid        guid   `xml:&quot;guid&quot;`<br>}<br><br>type guid struct {<br> IsPermaLink string `xml:&quot;isPermaLink,attr&quot;`<br> Value       string `xml:&quot;,chardata&quot;`<br>}<br><br>func main() {<br> url, ok := os.LookupEnv(&quot;INPUT_URL&quot;)<br> if !ok {<br>  log.Fatal(&quot;The url input is required.&quot;)<br> }<br><br> path, ok := os.LookupEnv(&quot;INPUT_PATH&quot;)<br> if !ok {<br>  log.Fatal(&quot;The path input is required.&quot;)<br> }<br><br> resp, err := http.Get(url)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to download the RSS feed: %v&quot;, err)<br> }<br><br> defer func() {<br>  _ = resp.Body.Close()<br> }()<br><br> if resp.StatusCode != http.StatusOK {<br>  log.Fatalf(<br>   &quot;Failed to download RSS feed. Status code: %d&quot;,<br>   resp.StatusCode,<br>  )<br> }<br><br> var rss rss<br> decoder := xml.NewDecoder(resp.Body)<br> if err = decoder.Decode(&amp;rss); err != nil {<br>  log.Fatalf(&quot;Failed to parse the RSS feed: %v&quot;, err)<br> }<br><br> for i := range rss.Channel.Items {<br>  pubDate, err := time.Parse(<br>   &quot;02 Jan 2006 15:04 -0700&quot;,<br>   rss.Channel.Items[i].PubDate,<br>  )<br>  if err != nil {<br>   log.Fatalf(&quot;Failed to parse the pubDate field: %v&quot;, err)<br>  }<br><br>  rss.Channel.Items[i].PubDate = pubDate.Format(<br>   &quot;2006-01-02T15:04:05-07:00&quot;,<br>  )<br> }<br><br> file, err := os.Create(path)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to create the file: %v&quot;, err)<br> }<br><br> defer func() {<br>  _ = file.Close()<br> }()<br><br> encoder := xml.NewEncoder(file)<br> encoder.Indent(&quot;&quot;, &quot;  &quot;)<br> if err = encoder.Encode(rss); err != nil {<br>  log.Fatalf(&quot;Failed to write the RSS feed: %v&quot;, err)<br> }<br>}</pre><p>Finally, I needed to package this up as a Docker container. Here’s my Dockerfile:</p><pre><br>FROM golang:1.24.0-bookworm AS build<br><br>WORKDIR /go/src/github.com/mfcollins3/hugoify-bluesky-rss-feed<br>COPY . .<br>RUN CGO_ENABLED=0 \<br>    GOOS=linux \<br>    GOARCH=amd64 \<br>    go build -v -o /opt/blueskyrss/bin/blueskyrss ./cmd/blueskyrss/main.go<br><br>FROM alpine:3.21.3<br><br>WORKDIR /opt/blueskyrss<br><br>COPY --from=build /opt/blueskyrss/bin/blueskyrss bin/<br><br>ENTRYPOINT [&quot;/opt/blueskyrss/bin/blueskyrss&quot;]</pre><p>This Dockerfile uses a multi-stage build to create one container that will compile my program using the Go compiler. The second container is then created based on Alpine Linux to run my program.</p><h3>Take-aways</h3><p>My first take-away from this process is that writing a custom GitHub Action was not as difficult as I first thought it was. Once I got over the learning hurdle to figure out how to get my input parameters, the rest of the process was pretty straightforward. I was able to test out my program, then publish the source code to the GitHub repo, and then consume my custom GitHub Action in my website’s workflow without any issues. And the end result was that I was able to get my Blue Sky posts on my website homepage.</p><p>The one downside is related to performance. The way that I packaged my GitHub Action, every time it is consumed in a workflow the Docker container needs to be built. On average, that takes about 20–25 seconds of build time. I can address this by taking another step and publishing the Docker container to <a href="https://docs.github.com/en/packages">GitHub Packages</a>. It might also be more performant to rewrite the GitHub Action to use JavaScript instead. But this is working, so I’ll leave exploring those for another blog post.</p><p>You can find the source code for my GitHub Action in the <a href="https://github.com/mfcollins3/hugoify-bluesky-rss-feed">mfcollins3/hugoify-bluesky-rss-feed</a> repository here. You can see it in action by looking at my <a href="https://github.com/mfcollins3/website">website repository</a>.</p><p><em>Originally published at </em><a href="https://michaelfcollins3.dev/blog/2025/03/bluesky-rss-feed-github-action/"><em>https://michaelfcollins3.dev</em></a><em> on March 12, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a31fc20a4f8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/a-github-action-for-importing-blue-sky-rss-feeds-a31fc20a4f8c">A GitHub Action for Importing Blue Sky RSS Feeds</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fair Use Licensing and Open Development]]></title>
            <link>https://medium.com/@mfcollins3/fair-use-licensing-and-open-development-088a564cfae1?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/088a564cfae1</guid>
            <category><![CDATA[software-licensing]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 07:00:25 GMT</pubDate>
            <atom:updated>2025-03-12T04:21:11.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eXFHlIKt_yydnyE4.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@lukesouthern?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Luke Southern</a> on <a href="https://unsplash.com/photos/open-led-signage-4kCGEB7Kt4k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>My ultimate career goal is to build and sell my own software products and services, but I want to do it in a fashion where I can develop software openly and let others see the source code that goes into a product while still protecting my commercial interests and ownership. In this post, I look at the different options and how fair-code may help me to achieve my intended goals.</p><p>I’ve been developing software professionally for over thirty years now. I have done a lot of programming over that time and built a lot of applications. I just crossed fifty years of age on January 31st. In my wildest hopes, I dream of going at least another thirty years. But while I enjoy contributing to the success of others and building software that customers enjoy, my biggest hope and dream is that someday I’ll finally sit down and start productizing my ideas, maybe build a company around them, and end my career with a string of successful software products that people will love. I don’t know that I ever want to fully retire. I love doing what I do and I want to build things as long as I can.</p><p>My main struggle when it comes to working on my own software products is that I don’t want to do it in isolation. I don’t want to be alone on the journey. I love the collaborative aspect of developing software. I love the feedback loop and getting ideas from my team not just on how I can make the product, but how I can make the source code better.</p><p>As an independent application developer, if I go with the traditional model of commercial software development, I can share the built application. I can host a web application on a secret domain. I can publish mobile applications and give access to it using Apple’s TestFlight service. But as a creator, I don’t feel fully satisfied with this <em>closed</em> approach. I want to be proud of the finished product, but I also want to be proud of the source code for the product as that’s the best part of the product. The product is great, but I want people to see what went into the product. I also want peers to be able to see what I built and learn from what I have done to improve their own products, or to learn and grow by using my code as inspiration for their continuing journey.</p><p>But the modern market has only given us two real models for software development: open source and closed source. Open source software uses open licenses such as <a href="https://opensource.org/license/MIT">the MIT License</a> or the <a href="https://opensource.org/license/apache-2-0">Apache License</a> which allow for open sharing of source code, but also allows for other developers to take others work and commercialize it. There’s also the dreadded <a href="https://opensource.org/license/gpl-3-0">GNU Public License</a> which is viral and infects everything that it touches, making everything free and open, which isn’t a bad thing, it’s just hard to make money off of that.</p><p>On the other side of the market is closed source licensing. In this model, source code is tagged as <em>proprietary and confidential</em> and is kept as a trade secret. Disclosing the source code for the product is a bad thing and exposes trade secrets to others to steal. People get to pay money to use the product, but they never see the source code. People can provide feedback and input about the final product, but they don’t get to <a href="https://learningenglish.voanews.com/a/are-you-prepared-to-see-how-the-sausage-is-made-/7138787.html"><em>see how the sausage is made</em></a>.</p><p>As an independent software producer, I ultimately want a business model where I can earn income from the products that I produce. This will help me to support myself and will ultimately help me continue to support my software as well as produce new products. As a software developer, programming is my art, how I express myself, and I want to share that part of me as well. I want people to appreciate the effort and creativity that went into my products. As someone who is interested in mentoring and growing others, I also want people to be able to use my source code to advance their skills. I don’t want people to steal my products or ideas and create competing products, but if I build a really cool control or implement a genius algorithm that can help someone else out with their product that doesn’t compete with mine, I’m not necessarily against that.</p><p>I was generally interested when I came across the <a href="https://faircode.io/">Fair-code website</a>. Fair-code defines a model where source code for commercial products can be shared, while protecting the economic and commercial rights of the original author. Software products can be developed in the open, but without having to give up the legal rights to solely be able to be compensated for the use of my products. Others can use my code for non-commercial use and internal business uses, but nobody else can sell my product. Individuals or companies can change my source code, and thus my product, for their own uses, but they can’t share those changes with others and make money off of them. Fair-code software licenses are being offered for many software products now:</p><p>The other trend that I’m seeing with some of these products is legally differentiating features that can be used under the fair-code license and <em>enterprise</em> features where the source code is still available, but they can’t be used under the fair-code license.</p><p>The logical argument against fair-code is that fair-code does allow individuals to take my source code and use it for non-commercial use. So, for example, if I create an iPhone application and sell it on the Apple App Store under a subscription license, someone that doesn’t want to pay me for the subscription can build the application themself and run it on their iPhone without paying me. Yes, they could do that, but will people, or the majority of people, really do that? If I build a mobile application that has a cloud backend required for the mobile application to work, is someone really going to spin up the Azure infrastructure and pay the fees to host the whole SaaS solution for their own personal use? Unlikely. It’s probably going to be cheaper for them to just pay my subscription fee and leverage the cloud services that all of my subscribers pay for. But it is a possibility.</p><p>I still have research to do on this topic, but fair-code sounds like a reasonable and useful approach to product development that achieves my goals. I want to be able to build products in the open and let people who are interested see what’s inside. I want to sell my products commercially to support myself and my family, and to provide me with the income to invest in new features and new products.</p><p><em>Originally published at </em><a href="https://michaelfcollins3.dev/blog/2025/03/fair-use-licensing/"><em>https://michaelfcollins3.dev</em></a><em> on March 11, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088a564cfae1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Development Containers]]></title>
            <link>https://medium.com/neudesic-innovation/introduction-to-development-containers-6fa62797ac07?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa62797ac07</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 07:00:51 GMT</pubDate>
            <atom:updated>2025-03-10T15:00:46.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PgYdB4Pa0JWgOoKm" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>As a manager and lead software developer, developer productivity is critical to me. I need to be able to onboard new developers quickly. I also need to make sure that all developers are using the right versions of software, programming languages, and tools. I also need to ensure that developers can run other services that our code depends on such as SQL databases. Development containers have been a huge improvement in reducing onboarding complexity and ensuring that I and my team are using the same tools to successfully build software solutions for customers.</em></p><p>If there’s been one innovation that has drastically affected my software development technique over the past year, and it’s not AI or LLMs, it’s been <a href="https://containers.dev/">development containers</a>. Development containers have been a game changer for me in the workflow that I use for developing software products involving APIs, microservices, databases, publish/subscribe messaging, etc. Development containers don’t help me out much with mobile application development, but one can dream of future improvements.</p><p>Development containers are a different way to use Docker containers. Instead of packaging your applications in a Docker container and running the container in a production environment, development containers let you package up your development tools and use the Docker container for development. Development containers work very similarly to connecting to a remote virtual machine using a tool such as SSH. The primary difference is the support of development environments to work with development containers provide a lot more tools.</p><p>The main software that I use that support development containers so far are <a href="https://code.visualstudio.com/">Visual Studio Code</a> and the <a href="https://jetbrains.com/">JetBrains</a> IDEs. I believe that <a href="https://visualstudio.com/">Visual Studio</a> also supports development containers, but I primarily use an Apple MacBook Pro and haven’t been able to verify how good the support is for it.</p><p>Why development containers? Here’s one scenario that happens to me a lot on software projects. When I begin a new software project for a customer, I sit down with the customer and my team and we figure out what programming languages and other software tools that we’re going to use for the project. Over time this could evolve and we can add or remove tools, or upgrade to newer versions as they come out. Before we begin working on the software, I or someone on the team will sit down and write out the README with incredible detail listing the exact development languages and tools and the specific versions that we are using. Now within the first week of the project, I&#39;ll get someone saying that some command isn&#39;t working correctly and they&#39;ll send me a screenshot on Microsoft Teams where the error is &lt;command&gt; was not found. My first question is whether they installed the tool. The typical answer is no. What was really meant is that they didn&#39;t spend the time to read the README before jumping into the source code.</p><p>Now, development containers doesn’t fully fix this, as there are some requirements necessary just to use development containers. But development containers makes the list of software to onboard smaller, and then the rest is handled by development containers. In the rest of this post, I’ll show you how to get started using development containers.</p><h3>Where You Can Run Development Containers</h3><p>Development container support is still evolving and features can be different between environments. There are three places where I’ve been able to use development containers:</p><p>I <em>believe</em> that Visual Studio also supports development containers, but I don’t have access to a Windows computer with Visual Studio installed so I cannot verify myself and I have not tested it out.</p><p>Visual Studio Code is the gold standard as of the time of this writing for running development containers. Visual Studio Code seems to support all of the features and has some extra added bonuses. One thing I really appreciate with Visual Studio Code’s implementation is supporing <a href="https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits">Git commit signing</a>. I prefer to sign my Git commits as an extra verification step so that when others see my commits, they can verify that they came from me. Originally, I uses GPG keys to sign my commits, but I have since switched to using <a href="https://www.1password.com/">1Password</a> and <a href="https://developer.1password.com/docs/ssh/git-commit-signing/">SSH keys</a>. When using GPG, I had to remember to change my public key ID for whichever development profile I was signing with (personal, business, corporate, or client). Using SSH, I can use a single key for all of my profiles and I just need to share the public key with GitHub or another tool to validate my commits.</p><p>Visual Studio Code implements SSH agent forwarding support so that I can sign my commits in the development container. When I sign the commit, Visual Studio Code forwards the SSH signing request to the SSH agent being run by 1Password on my host machine, and can complete the signature and commit in the development container.</p><p>JetBrains support is <em>good</em>, but I have not been able to get the SSH Git commit signing thing to work. When I work with development containers in JetBrains IDEs, I typically will create the container against a local copy of the Git repository on my development machine, and then I’ll use a terminal and Visual Studio Code in my host environment to sign the commits for changes that I make in the development container. I can deal with it, because there are times that I prefer to be working in a professional IDE like JetBrains.</p><p>I’ve played a little with development containers and GitHub CodeSpaces, but honestly, not enough to give you a full review. Maybe I’ll do that in a later blog post.</p><h3>Creating a Basic Development Containers</h3><p>For the rest of this post, I will be using Visual Studio Code to build and use development containers. To get started using development containers on your own, you’re going to need three things installed on your development machine:</p><ol><li><a href="https://code.visualstudio.com/">Visual Studio Code</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">Remote Development Extension Pack for Visual Studio Code</a></li><li><a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a></li></ol><p>Once all three are installed, you’re ready to go.</p><p>The first thing that you need is a base Docker container for your development container. The base Docker container is going to give you the Linux operating system and a starter set of tools that you’ll have available in your development container. Any Docker container can be used as a base container. It doesn’t need anything special. I typically start with a generic base container that Microsoft published in their public container registry at <a href="https://mcr.microsoft.com/">https://mcr.microsoft.com</a>. Microsoft makes several base containers available featuring programming languages like .NET, but I usually skip these and go straight to their <a href="https://mcr.microsoft.com/en-us/artifact/mar/devcontainers/base/about">generic base container</a>.</p><p>Microsoft’s generic base container comes with three options for the base Linux operating system: Alpine, Debian, or Ubuntu. I don’t usually use Alpine for development, although I do use it for my production containers. For development, I will usually use Debian (Bookworm, or Debian 12) or Ubuntu. For this article, I’ll use Ubuntu.</p><p>Inside of Visual Studio Code, I will create a new project in an empty folder. The first thing that I will do is to create a .devcontainer subdirectory and then create a devcontainer.json file in that subdirectory. Visual Studio Code will look in the root directory of projects for a .devcontainer subdirectory and a devcontainer.json file, and if it finds them, will ask you if you want to reopen the project in a development container.</p><p>The devcontainer.json file is the specification for the development container. This specification is used by Visual Studio Code to build and run the development container using Docker Desktop. devcontainer.json contains the base container image that you are going to use for the development container, along with a list of additional software to install that we&#39;ll get to in a moment, settings for Visual Studio Code or other tools, and a list of TCP/IP ports that should be forwarded to the host machine so that you can use a web browser to view a website hosted in the development container.</p><p>For the simple case, our devcontainer.json file will look like this:</p><pre>{<br>    &quot;name&quot;: &quot;basic-devcontainer&quot;,<br>    &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/base:1.2.3-ubuntu24.04&quot;<br>}</pre><p>This is the very minimum that you need to create a development container. If you have this, you can start your development container and use Visual Studio Code to attach to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*psyIhvc_2ChxYMDc.gif" /></figure><p>You now have a working development container! If you open a terminal inside of Visual Studio Code, any commands you run are executing from within the development container.</p><h3>Installing Additional Software in the Development Container</h3><p>This base container is only going to take us so far. It doesn’t have any programming tools, so while I can still use Visual Studio Code to write code, I can’t build it or run it. Let’s fix that now.</p><p>There are several ways that we can add additional software to our base container. We can create a Dockerfile based on the base container and use commands like apt-get to install packages or use RUN commands to run scripts to download and install software. We&#39;ll do this later in the article. We can also create a shell script that we can run after the development container is created but before we use it. In that shell script, we can add the commands to download and install the software. For many popular tools and programming languages, we can also use something called a <strong>feature</strong>. A feature is like a package specific for development containers. Others have created and published packages that can be reused by others to build and customize their own development containers. These features will install and configure software packages. We&#39;ll add a programming language by using a feature.</p><p>A list of available features that have been published are available <a href="https://containers.dev/features">here</a>. You can view the whole list or search for a specific package that you are interested in. Let’s say for this example that we want <a href="https://nodejs.org/">Node.js</a> to build a JavaScript application in our development container. We can add Node.js to our development container by adding and configuring the <a href="https://github.com/devcontainers/features/tree/main/src/node">Node.js feature</a>. We will update our devcontainer.json file by adding the feature to it:</p><pre>{<br>    &quot;name&quot;: &quot;basic-devcontainer&quot;,<br>    &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/base:1.2.3-ubuntu24.04&quot;,<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/node:1&quot;: {<br>            &quot;version&quot;: &quot;22.14.0&quot;<br>        }<br>    }<br>}</pre><p>The ghcr.io/devcontainers/features/node URI tells Visual Studio Code where it can find the feature&#39;s definition. This is a browsable URL. <a href="https://ghcr.io/devcontainers/features/node">Click this to see</a>. The 1 is the version number or tag for the feature. The version number uses <a href="https://semver.org/">Semantic Versioning</a>. We can use a specific version such as 1.6.1 (the latest version at the time of writing) or a generic version number such as 1, which indicates to use the latest version with the major version number 1.</p><p>Inside of the feature specification, I provided a value for the version field. Many features allow you to specify the version number of the tool that you want to install, with the default being the latest version. For programming languages and development tools, I like to specify the version number to make it official and to keep developers working on the exact same version of tools. This insulates the development team from any bugs that may be introduced by team members using different tool versions. In this example, I am specifying that I want the project to use Node.js 22.14.0. Within the development container, all developers will be using that version.</p><h3>Customizing the Base Container</h3><p>In certain cases, I need to customize the base container to install something that can’t be addressed by a feature. In that case, I need to create a new Docker container based on the base container, but with my customizations. I can do this by creating a Dockerfile and updating my devcontainer.json to reference the Dockerfile. When I do this and open my development container in Visual Studio Code, Visual Studio Code will use the Dockerfile to build the new development container image before launching the development container. We can reuse the same base container image specified in devcontainer.json when building the new development container image. Here&#39;s a Dockerfile:</p><pre>FROM mcr.microsoft.com/devcontainers/base:1.2.3-ubuntu24.04<br><br># gnupg2 is required for Git commit signing to work in the development<br># container.<br>RUN apt-get update &amp;&amp; apt-get install -y gnupg2</pre><p>In this example from one of my development containers, I’m installing gnupg2 into the container to support Git commit signing using GPG. (I don&#39;t technically need this anymore now that I&#39;ve switched over to SSH commit signing, but I still usually include it for developers that don&#39;t have 1Password).</p><p>I also typically create a .dockerignore file to exclude the development container files from being uploaded to the Docker daemon when the development container image is created:</p><pre>.dockerignore<br>devcontainer.json<br>Dockerfile</pre><p>We can next update our devcontainer.json specification to look like this:</p><pre>{<br>    &quot;name&quot;: &quot;custom-devcontainer&quot;,<br>    &quot;build&quot;: {<br>        &quot;context&quot;: &quot;.&quot;,<br>        &quot;dockerfile&quot;: &quot;Dockerfile&quot;<br>    },<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/node:1&quot;: {<br>            &quot;version&quot;: &quot;22.14.0&quot;<br>        }<br>    }<br>}</pre><p>The presence of the build field in devcontainer.json tells Visual Studio Code that it needs to build the development container image using Dockerfile. The context field tells Visual Studio Code to use the .devcontainer subdirectory as the <em>context</em> for where Dockerfile and other files necessary for the development container can be found.</p><h3>A Development Container with Service Dependencies</h3><p>It’s rare that I build any software that does not have dependencies. At a minimum, I’m going to have a database such as <a href="https://azure.microsoft.com/en-us/products/azure-sql/">Azure SQL</a> that I’m using to persist application data. Development containers can have more than one container image using <a href="https://docs.docker.com/compose/">Docker Compose</a>. Docker Compose can be used to launch multiple containers and connects the containers using a virtual network so that they can interact and work with each other. As developers, we can craft our development container to have all of the dependencies necessary (or something close enough to simulate it such as Microsoft SQL Server for Azure SQL) to build, run, and test our applications in the development container.</p><p>To begin with, we’ll create a compose.yaml specification that tells Docker Compose how to build and run our development container:</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    volumes:<br>      - ..:/workspace:cached<br>    command: sleep infinity<br>    # Required for ptrace-based debuggers like C++, Go, and Rust<br>    # See https://code.visualstudio.com/docs/devcontainers/create-dev-container#_use-docker-compose<br>    cap_add:<br>      - SYS_PTRACE<br>    security_opt:<br>      - seccomp:unconfined</pre><p>This specification tells Docker Compose to create a container named app based on Dockerfile. The app container will mount the root directory of my local Git repository in the app container at /workspace. When the app container is started, it will execute the sleep infinity command. Because our development container is not running any kind of service, if we start it without a command, the development container will stop immediately and unload. By running it with the sleep infinity command, we keep the development container alive so that Visual Studio Code can attach to it and we can get terminal access to the development container.</p><p>We can now update our devcontainer.json file to use Docker Compose:</p><pre>{<br>    &quot;name&quot;: &quot;my-project&quot;,<br>    &quot;dockerComposeFile&quot;: &quot;compose.yaml&quot;,<br>    &quot;service&quot;: &quot;app&quot;,<br>    &quot;workspaceFolder&quot;: &quot;/workspace&quot;,<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/node:1&quot;: {<br>            &quot;version&quot;: &quot;22.14.0&quot;<br>        }<br>    }<br>}</pre><p>I also update my .dockerignore file to exclude compose.yaml:</p><pre>.dockerignore<br>compose.yaml<br>devcontainer.yaml<br>Dockerfile</pre><p>Now if I add a service dependency so that I can develop against it, I can add it to compose.yaml. Using my previous example, if I&#39;m building a solution that is being targeted for <a href="https://azure.microsoft.com/en-us">Microsoft&#39;s Azure Cloud</a>, I may use Azure SQL for my persistent data. But I can&#39;t run Azure SQL locally. I can always use a cloud instance, but it&#39;s not as convenient as having a local database to work with. But what I can do is run Microsoft SQL Server. While not 100% compatible, they&#39;re pretty close. Microsoft also makes Microsoft SQL Server available as a <a href="https://mcr.microsoft.com/en-us/artifact/mar/mssql/server/about">Linux-based container</a>. We can add it to our compose.yaml file:</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    volumes:<br>      - ..:/workspace:cached<br>    command: sleep infinity<br>    # Required for ptrace-based debuggers like C++, Go, and Rust<br>    # See https://code.visualstudio.com/docs/devcontainers/create-dev-container#_use-docker-compose<br>    cap_add:<br>      - SYS_PTRACE<br>    security_opt:<br>      - seccomp:unconfined<br><br>  sqlserver:<br>    image: mcr.microsoft.com/mssql/server:2022-CU16-ubuntu-22.04<br>    environment:<br>      - ACCEPT_EULA=Y<br>      - MSSQL_PID=Developer<br>      - MSSQL_SA_PASSWORD=${MSSQL_SA_PASSWORD}<br>    ports:<br>      - &quot;1433:1433&quot;<br>    volumes:<br>      - sqlserver_data:/var/opt/mssql<br><br>volumes:<br>  - sqlserver_data:</pre><p>When I start my development container now, Visual Studio Code is going to launch and connect to my development container, but it’s also going to start Microsoft SQL Server. And both the development container and SQL Server will be connected to the same virtual network, so my programs running in the app service can connect to SQL Server using the hostname sqlserver.</p><p>This is an incredible feature that makes building complex services incredibly easy. If I need <a href="https://redis.io/">Redis</a>, I can add a Redis container. If I need a publish/subscribe asynchronous message broker, I can add <a href="https://www.rabbitmq.com/">RabbitMQ</a>. And unlike using Docker Compose on its own, I don’t need to remember to start everything before I begin developing. The services are all started at the beginning of my development session and stopped at the end. If I switch between projects, my environment will change automatically.</p><h3>Where Can’t I Use Development Containers?</h3><p>Development containers are great for full-stack and microservice development, but when working with client applications, they’re not the right solution. I do a lot of mobile development, especially with <a href="https://developer.apple.com/xcode">Xcode</a> for building iOS applications. Development containers are based on Linux, not macOS, so I can’t use them. Now I can use a development container to host my services and APIs and have the mobile application call them using HTTP, but I can’t do mobile application development in development containers. Desktop development also wouldn’t work here.</p><p>Web development can be done inside of a development container, but debugging using a professional IDE such as JetBrains or the Visual Studio Code debugger may not work so well. The reason is that the web browser is going to run in the host environment and access the web server that is accessible through a TCP/IP port that has been forwarded from the development container to the host environment. The debugger, which is running in the development container, can’t connect to the web browser to do debugging. You can debug using the in-browser development tools, but sometimes you really just want to debug in the IDE.</p><h3>Testing APIs</h3><p>I mentioned this in the previous section. While I can’t use development containers for client application development, I can test my client application calling APIs in my services that are running in the development container. There are two ways to do this. The first is that I can forward a TCP/IP port from my development container to the host environment, allowing a program running on my computer to connect to a service running in the development container. This is often used for connecting a web browser to a web server running inside of the container.</p><p>Another option is to use a port tunneling tool like <a href="https://ngrok.com/">ngrok</a>. ngrok publishes a <a href="https://hub.docker.com/r/ngrok/ngrok">Docker container</a> that you can add as a service to your compose.yaml file to create a secure tunnel to your development container&#39;s virtual network. The ngrok container will create a secure tunnel with a customizable domain or URL to the public Internet. Your client applications can then use that domain or URL to send requests to your development container. The ngrok container can forward all incoming requests to your app service on whatever TCP/IP port your program is listening on.</p><p>I will go into this deeper in a future blog post with an example.</p><h3>Conclusion</h3><p>Development containers have been one of the biggest productivity boosters for me as a microservice and full-stack developer over the last couple of years. The integration between Docker technologies and IDEs like Visual Studio Code and JetBrains have made it easy to set up a complete development environment and fix long onboarding times for new developers. Using development containers in my own projects means that developers can get up and running in minutes instead of having to read through long lists of required software and dealing with version conflicts, compatibility issues, and long installation times in their development environments.</p><p>In future posts, I’ll share some real stories and show you how I’m using development containers in more detail.</p><p><em>Originally published at </em><a href="https://michaelfcollins3.dev/blog/2025/03/development-containers/"><em>https://michaelfcollins3.dev</em></a><em> on March 9, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa62797ac07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/introduction-to-development-containers-6fa62797ac07">Introduction to Development Containers</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Adaptive iOS Applications Using Flutter]]></title>
            <link>https://medium.com/neudesic-innovation/build-adaptive-ios-applications-using-flutter-5a0631830a15?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a0631830a15</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 06:40:35 GMT</pubDate>
            <atom:updated>2022-03-12T06:40:35.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4L2bY5h2JcyNnYnI" /><figcaption>Photo by <a href="https://unsplash.com/@danielkorpai?utm_source=medium&amp;utm_medium=referral">Daniel Korpai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the mobile space, there are many form factors and screen sizes that you have to take into consideration when designing your application. Flutter provides a great framework for building responsive applications that can adjust their layout to the size of the screen or host window. But when using Flutter to develop a user experience specific to iOS and iPadOS, there’s one thing missing from Flutter: size classes. In this article, I will show you how to extend your Flutter iOS application to be able to use iOS size classes to build adaptive UIs for iPhone and iPad.</p><h4>About iOS Size Classes</h4><p>In the early years of the iPhone, Apple released one phone model per year. Initially, all of the phone models maintained the same resolution from year-to-year. That made it easy to build an iPhone application because there was only one single screen size. After a few years, Apple started introducing multiple models of phones, and then the screen sizes started to differ. Then Apple introduced the iPad which brought with it a completely different screen resolution. And then there were retina displays. And then Apple introduced multitasking which allows the user to run two apps concurrently on the screen and allows the user to adjust the screen so that one application has more space or both applications have equal space on the screen.</p><p>To make it easier for application designers to design adaptive user interfaces, Apple introduced the concept of size classes. There are two size classes: <strong>regular</strong> and <strong>compact</strong>. Depending on the device and the orientation, the horizontal size class and vertical size class will either be <strong>regular</strong> or <strong>compact</strong>. An iPad Pro in either portrait or landscape mode is going to have both a horizontal and vertical size class of <strong>regular</strong>. An iPhone 13 in portrait mode will have a horizontal size class of <strong>compact</strong> and a vertical size class of <strong>regular</strong>. In landscape mode, the iPhone 13 will have both size classes set to <strong>compact</strong>.</p><p>For an iPad Pro that supports multitasking, when the applications are in portrait mode, the horizontal size class will be <strong>compact</strong> and the vertical size class will be <strong>regular</strong>. Then the iPad Pro is in landscape mode and have equal space on the screen, both applications have a horizontal size class of <strong>regular</strong> and a vertical size class of <strong>regular</strong>.</p><p>The concept of size classes allows iOS developers to adapt their user experiences to the available space on the device based on size classes instead of having to know the specific width or height of the screen. Controls can be shown or hidden, or even entire user experiences changed, based on the size class. For example, on an iPad with <strong>regular</strong> x <strong>regular</strong> size classes, the user experience may be based on a two or three column split view like the Mail app. On an iPhone or in a reduced multitasking scenario, the user experience may change and use a tabbed layout.</p><p>For more information on size classes, read <a href="https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/">Adaptivity and Layout</a> in the iOS Human Interface Guidelines.</p><h4>The Argument for Size Classes on iOS</h4><p>Flutter has excellent tools for building responsive applications using MediaQuery and LayoutBuilder, but to use them requires knowing specific a specific width or height to use to adjust the layout. While this can certainly be done, it’s not as easy or friendly as laying out a compact user interface versus a regular user interface like we can do with size classes. When building a Flutter user experience based on the <a href="https://api.flutter.dev/flutter/cupertino/cupertino-library.html">Cupertino</a> widget set, you want to build a user experience that is as close to the native iOS look-and-feel as possible. To get it completely right, we need support for being able to build device adaptive user experiences using size classes, especially when we want to target the iPad as well as the iPhone.</p><h4>Add Size Class Support to the iOS Runner App</h4><p>I want to target iPad as well as iPhone for my Flutter application. On the iPad, I also want to support multiple windows and multitasking. To do that, I need a way for the host view controller to be able to notify the Flutter widget tree that the size classes change when the user rotates the device or enters multitasking mode. I determined that the best way to do this is to use a Flutter event channel. Using an event channel, my native code can raise events when the size classes change and the Flutter widget tree can receive those events and adapt to the updated size classes.</p><p>On iOS, the horizontal and vertical size classes are part of the <em>traits</em> of the application and are part of the UITraitCollection object that is available to all view controllers from the traitCollection property. When the traits change, the traitCollectionDidChange(_:) function on the view controller is called with the updated trait collection. I can use traitCollectionDidChange(_:) to fire events containing the new size classes to the Flutter widget tree.</p><p>The first thing that I need to implement is a FlutterStreamHandler object that Flutter can use to subscribe to receive events from the host iOS application. I defined the TraitCollectionStreamHandler class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/564188da82f25a7b7be53ddbd170ca00/href">https://medium.com/media/564188da82f25a7b7be53ddbd170ca00/href</a></iframe><p>The next(_:) function will take a UITraitCollection object and will serialize it in a map to be sent to the Flutter code. While there are other traits that may be interesting, for this article I only care about the horizontal and vertical size classes. The onListen(withArguments:) function is called to link the TraitCollectionStreamHandler with the subscriber. onListen(withArguments:) sends the current trait collection for the parent view controller to the new subscriber to seed the stream.</p><p>Flutter provides the FlutterViewController class to host the Flutter view. I can subclass FlutterViewController and create the AdaptiveFlutterViewController class to create the event stream and forward trait collection changes to subscribers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90dc6f58c12d79ba2d8f26a5562ce7cf/href">https://medium.com/media/90dc6f58c12d79ba2d8f26a5562ce7cf/href</a></iframe><p>I can then use AdaptiveFlutterViewController to host my Flutter application by using it in my scene delegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d52aab7ee961ba832763703c4dbf0d18/href">https://medium.com/media/d52aab7ee961ba832763703c4dbf0d18/href</a></iframe><p>And I can launch the scene and manage the Flutter engine group in my custom AppDelegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c133712aea1d6a4ab9b8d59d4ac99753/href">https://medium.com/media/c133712aea1d6a4ab9b8d59d4ac99753/href</a></iframe><h4>Add Size Class Support to Flutter</h4><p>Now that the iOS side is complete and size class updates are being published to the event channel, I need to implement the Flutter side of the app to capture and update the user experience when the size classes change. The first thing that I need to do is to introduce the size classes into Flutter. I will create an enumeration named CupertinoSizeClass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da7679a4947e986a797beb60a6e7bba2/href">https://medium.com/media/da7679a4947e986a797beb60a6e7bba2/href</a></iframe><p>The index values match the integer values on iOS. The integer values are passed from the iOS Runner app to the Flutter app, so 0 will correlate to unspecified, 1 will correlate to compact, and 2 will correlate to regular.</p><p>To make it easier to pass around the size classes and future traits, I will create a data class that I will deserialize the event into:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5354fac0bf43e3e23f4134cb972a2e0e/href">https://medium.com/media/5354fac0bf43e3e23f4134cb972a2e0e/href</a></iframe><p>I need a widget that my Flutter application can use to adapt the user experience to the current size class and will cause the widget tree to be rebuilt when the size classes change. I can expose the size classes to the widget tree by creating a new InheritedWidget named CupertinoTraitQuery:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff70f9a2524df0dc3b24a909d021d30/href">https://medium.com/media/6ff70f9a2524df0dc3b24a909d021d30/href</a></iframe><p>CupertinoTraitQuery exposes the horizontalSizeClass and verticalSizeClass properties to descendent widgets in the widget tree. When the size classes change, the child widgets will be updated with the new values of the size classes.</p><p>To wrap the CupertinoTraitQuery widget and automatically inject it into the widget tree, I created the CupertinoAdaptiveWidget widget class. CupertinoAdaptiveWidget can be used as the root widget for a widget tree that needs to adapt based on the size classes (or other future traits). CupertinoAdaptiveWidget will subscribe to receive events from the event channel and will rebuild the widget tree when the traits change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890e3cad0b058f19071310950bbeaafe/href">https://medium.com/media/890e3cad0b058f19071310950bbeaafe/href</a></iframe><p>In CupertinoAdaptiveWidget, I created _createTraitCollection to convert an event from the event channel to a CupertinoTraitCollection object. I am then using a StreamBuilder widget to subscribe to the event channel and update the widget tree when new trait updates are received from the stream.</p><p>I can now create adaptive applications by using CupertinoAdaptiveWidget in the widget hierarchy. I’m using it in my test as the child of my CupertinoApp widget, but it may be better as the parent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99cda10aabb31871940137e964d81eec/href">https://medium.com/media/99cda10aabb31871940137e964d81eec/href</a></iframe><h4>Testing Size Classes</h4><p>For a quick test, I created a HomeScreen widget that simply outputs the current size classes for the device:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97985bd30c2678a744336867fb6856f8/href">https://medium.com/media/97985bd30c2678a744336867fb6856f8/href</a></iframe><p>On the iPhone 13 simulator in portrait mode, I can see that my size classes are <strong>compact</strong> width and <strong>regular</strong> height:</p><figure><img alt="The image shows an iPhone 13 in portrait mode. The screen shows that the horizontal size class is compact and the vertical size class is regular." src="https://cdn-images-1.medium.com/max/216/1*BqIXc126NnSEmGz7kJ7L4w.png" /><figcaption>iPhone 13 in portrait mode</figcaption></figure><p>When I rotate the iPhone 13, my size classes change to <strong>compact</strong> width and <strong>compact</strong> height:</p><figure><img alt="The image shows an iPhone 13 in landscape mode. The screen shows that the horizontal and vertical size classes are compact." src="https://cdn-images-1.medium.com/max/760/1*2Gg1hPfft_Q8TLdS7tUiqA.png" /><figcaption>iPhone 13 in landscape mode</figcaption></figure><p>My size class implementation appears to be working.</p><h4>Where Have We Gone</h4><p>Flutter has good support for building responsive user interfaces, but if you’re really focusing on building iOS-like applications in Flutter to run on iPhone and iPad, programming with size classes makes building adaptive user experiences easier. In this article, I showed how to use an event stream to publish the initial size classes and publish changes to the size classes at runtime. I then showed how to build widgets that can receive and process the changes to the size classes and update the application’s user experience by adapting to the size classes for the application. Hopefully as you build iPhone and iPad applications using the Cupertino widget collection, you can build fully-adaptive iOS-like apps that support multiple scenes and multitasking based on size classes, just like you do in native development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a0631830a15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/build-adaptive-ios-applications-using-flutter-5a0631830a15">Build Adaptive iOS Applications Using Flutter</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing SwiftUI State Using Redux]]></title>
            <link>https://medium.com/neudesic-innovation/managing-swiftui-state-using-redux-525a8879c1be?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/525a8879c1be</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[flux]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 02:44:35 GMT</pubDate>
            <atom:updated>2022-02-21T02:44:35.412Z</atom:updated>
            <content:encoded><![CDATA[<h3>Managing SwiftUI State Using A Redux-Like Framework</h3><p>Model View Controller was a game changer pattern in the development of user experiences for customers. Applying a pattern with specific roles between the Model, the View, and the Controller helped to clarify and make simpler the planning and development of user interfaces. It also helped to make it possible to unit test UI behavior by moving testable code out of the View and into the Controller. MVC also led to the creation of similar patterns such as Model View ViewModel (MVVM) and Model View Presenter (MVP) which further clarified roles and enhanced the MVC pattern.</p><p>But with every positive thing, MVC also had its downsides. As multiple view user interfaces developed, there were subviews and view transitions and navigation paths that needed to be followed, which meant that state had to flow from one view to the next, and in the case of modal views, that state also had to flow back. Then with the rise of multi-core CPUs, asynchronous code and multithreading brought new challenges to state management and keeping views up to date. Lots of different solutions came about for how to handle that. Facebook ran into this issue head-on and came up with a pattern named <a href="https://facebook.github.io/flux/">Flux</a> to resolve it.</p><p>Flux introduced the concept of a unidirectional data flow in user interfaces. Instead of passing state around between views, they created a singular state store that was their <em>single source of truth</em>. Views would read from the state store to get the current state and present it. User interaction would result in <em>dispatching</em> actions that would <em>mutate</em> the application state. The result of the mutation was that the views would get an updated state to use to update the contents of the view.</p><p>Flux has also led to what is called the <strong>Data Down, Actions Up</strong> architecture. In this architecture, data flows logically <em>down</em> from the state store to the application. When the application has updates to the state, actions are <em>dispatched</em> up to the store which is responsible for mutating and updating the state and notifying the application of the new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*IaLPPj4azBm66E4yko2ePg.png" /><figcaption>Data Down, Actions Up Pattern</figcaption></figure><p>With Flux’s single source of truth and the unidirectional data flow, the user interface architecture can become easier to manage. User interface development now becomes similar to a pipeline. Components do not need to manage multiple references to other components in most cases. They only need to be aware of the next component in the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLQIpXb6mR9B6tb7z83zbA.png" /><figcaption>A unidirectional flow of data and actions for a UI</figcaption></figure><p>This architecture can be further simplified by removing the need for components to know about each other at all when combined with a <em>coordinator</em> pattern that packages up all of the components into a single unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Uz5jL6-ISVc1ecoPe99c6Q.png" /><figcaption>The unidirectional architecture with a Coordinator wrapping the components</figcaption></figure><p>Since the introduction of the Flux pattern, there have been many refinements and implementations of the pattern such as <a href="https://redux.js.org/">Redux</a> and <a href="https://mobx.js.org/README.html">MobX</a>. In this article, I will present how to implement a pattern such as Redux in Swift for use with a SwiftUI application.</p><h4>Redux as an Abstract Data Type</h4><p>If you have gone through any kind of academic computer science course, you have undoubtedly heard the phrase <em>Abstract Data Type</em>. For those that have not, an Abstract Data Type presents a model of an algorithm or data structure from the perspective of the user or consumer. I am going to start my exploration of my Redux implementation by defining the implementation as an Abstract Data Type.</p><p>Using the images in the last section, we know that there are three immediate parts to Redux:</p><ul><li>A <strong>store</strong> that holds the <strong>state</strong> and is responsible for mutating the <strong>state</strong> in response to the receipt of <strong>actions</strong>. The <strong>store</strong> notifies observers when a new <strong>state</strong> is available.</li><li>A <strong>state</strong> value which is data that controls how the application behaves. Application <strong>state</strong> could be a single value or an envelope data structure containing smaller data structures and other data.</li><li><strong>Actions</strong> are events that are sent to the <strong>store</strong> to indicate how the <strong>state</strong> must change.</li></ul><p>The <strong>store</strong> has additional rules that we must follow:</p><ol><li><strong>Actions</strong> need to be interpreted in the order in which they are received. Two or more <strong>actions</strong> cannot update the <strong>state</strong> at the same time.</li><li>Mutating the <strong>state</strong> must be an atomic operation. An atomic operation means that the application can’t read or change the <strong>state</strong> while the <strong>state</strong> is being mutated.</li><li>We must recognize that the majority of modern mobile applications are concurrency beasts. They use pools of threads to perform asynchronous operations, all of which may cause updates to the application’s <strong>state</strong>. We need to ensure that the <strong>state</strong> is updated safely.</li></ol><p>We can model our pattern as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUM_gN2CtB3d0GAJs5rr1w.png" /><figcaption>Class diagram showing the Store interface</figcaption></figure><p>In this diagram, we have a State class, a Store class, and an Action interface. The Store class maintains the current state. Store exposes a dispatch method that will accept an Action value that will result in the state value to be updated with a new state. Store also maintains a list of observers that it will notify when changes to state occur.</p><h4>Implementing a Basic State Store</h4><p>Given the Abstract Data Type, how should I define this in Swift and meet the requirements of the pattern? Fortunately, Swift 5.5 has made this much easier with the introduction of <strong>actors</strong>. Prior to Swift 5.5, serializing access to the state and serializing the execution of the actions would have had to be done using a serial DispatchQueue. However, with Swift actors, we have a better way of implementing this.</p><p>Swift actors are similar to classes, but they have additional features. Actors in Swift serialize access to its properties and methods, meaning that an actor can only be accessed by code from one thread at a time. This feature of actors allows me to model the store as an actor and ensure that one thread cannot be reading the state while another thread is updating it.</p><p>I am going to use Swift generics to implement my store. This will allow me to hold off on giving an actual shape to either the state or the actions until I’m a little further down. Using generics, I can get by with just knowing that there will be a state and action type eventually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c7afc5c8ad4edcaa62f2502f72d6ae/href">https://medium.com/media/35c7afc5c8ad4edcaa62f2502f72d6ae/href</a></iframe><p>This first attempt isn’t going to work though because I’m already seeing a compiler error. There’s nothing initializing the state property. I need an initializer for Store. I can add one to fix this error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0544edc7a3c5701b7b6b2166b657a1e9/href">https://medium.com/media/0544edc7a3c5701b7b6b2166b657a1e9/href</a></iframe><p>This fixes the compiler error. Now I need to turn my attention to the dispatch(action:) method to update the state. I can implement dispatch(action:) to interpret the action and update state, but then my Store really wouldn’t be generic and reusable because it would have too much knowledge of State and Action. What I need is to provide a generic means for the Store to interpret the Action and mutate the State. Using Redux for inspiration, Redux uses a concept called a <strong>reducer</strong>.</p><p>In Redux, a <strong>reducer</strong> is a <strong>pure function</strong> that takes the current state and the action to execute as parameters and produces a new state. A pure function is a function that, when given the same inputs, produces the same outputs and has no side effects. A reducer will receive everything that it needs as parameters. It has no ties to any outside entities. It does not change the existing state. It only produces a new State value. I’ll add a reducer to my Store type and will implement the dispatch(action:) method to use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c10ff81bfc657e4aed153d47b9b963ba/href">https://medium.com/media/c10ff81bfc657e4aed153d47b9b963ba/href</a></iframe><p>So far, this looks good, but we have not seen it in action yet. To test the action, I will implement a simple counter demo. When the application starts, the user will see the current count, which will be zero, and a button to tap to increment the count by one. Tapping the button will dispatch an action to the store to increment the counter. Because my Store actor implements ObservableObject, SwiftUI will subscribe to changes in the state and will update the UI with the new value of the count property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2bf0a7e8dc4fea1ecc0a27921db4731/href">https://medium.com/media/f2bf0a7e8dc4fea1ecc0a27921db4731/href</a></iframe><p>Immediately, I run into two compiler errors with this code:</p><ul><li>Actor-isolated property &#39;state&#39; can not be referenced from the main actor</li><li>Actor-isolated instance method &#39;dispatch(action:)&#39; can not be referenced from the main actor</li></ul><p>These errors mean that because of the new concurrency model introduced in Swift 5.5, I cannot just directly access the Store actor. Because Store serializes access to its properties and methods, all access to Store needs to be asynchronous because calls may be blocked while other code is accessing Store.</p><p>The first error is the more problematic one. I need to be able to access the current state from the main thread. I cannot use the await keyword in SwiftUI to access the Store.state property. What I need is a way that safely exposes Store.state to the main thread of the application. Fortunately, SwiftUI provides us with the @MainActor attribute.</p><p>The @MainActor attribute, when applied to either a property or function, will force the application to read or write a property or invoke a method or function on the main thread of the application. If I apply @MainActor to my Store actor, this should fix these errors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e90d971e25b2d2a60db77821e8222bb7/href">https://medium.com/media/e90d971e25b2d2a60db77821e8222bb7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*YXmsJ9bnAnhb7sqLDjVLDQ.png" /><figcaption>The application showing that dispatching an action increments the counter</figcaption></figure><p>This change fixes my errors and the applications works, but it’s not ideal. Forcing all calls to update the state to the UI thread isn’t realistic and defeats the purpose of using an actor. An actor is intended to be called by multiple threads. Additionally, a reducer may take a long time to run and it would be better for the reducer to be able to run asynchronously if necessary.</p><p>The other problem is that the initializer for Store also needs to have @MainActor to initialize the state property. This would mean that we can only create a Store instance on the main thread. This actually isn’t a significant problem though because in most cases Store will be created from the main thread, but I for some reason still do not like putting the @MainActor constraint on my initializer. In order to remove @MainActor from the initializer, I need to find a way to initialize the state property. What I am going to do is change State into a protocol and require that the State type have a default initializer. I am also going to change the reducer to be an asynchronous function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f81f1462135064e842a37999a0091d77/href">https://medium.com/media/f81f1462135064e842a37999a0091d77/href</a></iframe><p>I then have to update my application by conforming ApplicationState to the State protocol and dispatching the button’s action within a Task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86760b87b4102cc7384a3909cd514323/href">https://medium.com/media/86760b87b4102cc7384a3909cd514323/href</a></iframe><p>This works, but it’s still not good. Going back to my first requirement above, actions need to be executed in the order that they run. Because my dispatch(action:) method has two await calls in it, this could technically allow other threads to get in an update the state while one action is being executed. This brings me to a tough decision. Either I have to be ok with this, or I have to run the reducer and update the state on a single thread, such as the main thread. And if I do it on the main thread, long running code in the reducer could block the main thread. If I push the reducer execution onto the main thread, then I have to keep the reducer fast and simple, which means no execution of asynchronous code in response to an action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9116388bca4d01009d394f7e7db76c/href">https://medium.com/media/ae9116388bca4d01009d394f7e7db76c/href</a></iframe><p>With this latest iteration, my Store actor can be initialized on any thread, called on any thread, and is safe to be run from the UI. The only drawback is that the reducer must run on the main thread to update the state atomically and therefore it must be kept simple and fast without any asynchronous logic.</p><p>So what happens if I want to run asynchronous logic? There are a couple of approaches that we can take to that. First, I can create an overload that takes a factory method that can run asynchronously and produce an Action to be evaluated by the reducer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/008d0c3f84d8871dc253d3ee0a51701d/href">https://medium.com/media/008d0c3f84d8871dc253d3ee0a51701d/href</a></iframe><p>The downside to this approach is that if I need to run the same asynchronous code from multiple places, it is not as convenient as dispatching an Action to the Store. We need something else that will help us to extend Store and allow us to handle more scenarios that include complex actions that perform asynchronous logic. More specifically, we need a way to dispatch an Action to the Store that executes asynchronous logic and produces another Action that causes a simple state update. We need middleware.</p><h4>Enter Middleware</h4><p>If you jumped on the early <a href="https://nodejs.org/">Node.js</a> and <a href="https://expressjs.com/">Express</a> bandwagon, then you are probably familiar with the concept of middleware. In Express, handling HTTP requests involves creating a pipeline of actions where the request and response objects are sent to the first item in the pipeline and are then passed down the pipeline to the next element until the end is reached. When the end is reached, the response is returned to the client. This is similar to what we need. When an Action is dispatched to the Store, we want a pipeline where we can send an Action to the first item in the pipeline. Each item in the pipeline can do one of the following:</p><ul><li>Pass the action to the next item in the pipeline without further processing.</li><li>Operate on the action, and then pass the action to the next item in the pipeline.</li><li>Execute some behavior and replace the action with a new action that is sent to the next item in the pipeline.</li><li>Interpret the action and terminate the pipeline.</li></ul><p>What we need to add to the Store implementation is extensibility that cannot be achieved only through the reducer. We need a middleware pipeline that can pre-process actions before they update the application’s state.</p><p>I am going to start off by defining the Middleware protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d810ad1349f5e0d40a214fc3997831a8/href">https://medium.com/media/d810ad1349f5e0d40a214fc3997831a8/href</a></iframe><p>The Middleware protocol uses Swift’s <a href="https://www.vadimbulavin.com/call-as-function-in-swift/">Callable Object</a> feature to allow a Middleware instance to be called as if it were a Swift function. At execution time, the callAsFunction(action:) method will be invoked. The Middleware protocol has an associated Action type that describes the type of the action consumed and produced by the middleware. The output of callAsFunction(action:) is optional. If an Action is not returned, the pipeline will terminate without updating the state in the Store actor.</p><p>I can try to add a Middleware property to the Store actor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16636d0b6e799ed8210ea134f20607fb/href">https://medium.com/media/16636d0b6e799ed8210ea134f20607fb/href</a></iframe><p>This will fail, however, with the bane error of Swift: Protocol &#39;Middleware&#39; can only be used as a generic constraint because it has Self or associated type requirements. Because Middleware has an associated type, we can only use it as a constraint, but not use Middleware directly. In order to support using Middleware, we have to use a technique called <strong>type erasure</strong>. I will define a new type that conforms to Middleware called AnyMiddleware&lt;Action&gt;:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/652f4abf61b90855de0e5c2a755300ff/href">https://medium.com/media/652f4abf61b90855de0e5c2a755300ff/href</a></iframe><p>AnyMiddleware&lt;Action&gt; wraps another Middleware instance, but provides a type safe wrapper that can be used to store references to Middleware instances. AnyMiddleware&lt;Action&gt; itself conforms to Middleware, and when called will invoke the wrapped middleware. I also defined a Middleware extension function named erasetoAnyMiddleware() that will wrap any Middleware instance and will return the AnyMiddleware&lt;Action&gt; wrapper.</p><p>I can now update my Store implementation to use middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8a38697832aee1dc9cdc3d290d518c7/href">https://medium.com/media/f8a38697832aee1dc9cdc3d290d518c7/href</a></iframe><p>In this implementation, I have added a middleware property and a second initializer that accepts the Middleware to use. Specifying a Middleware is optional, and if not specified, an instance of EchoMiddleware&lt;Action&gt; will be used. I updated the dispatch(action:) method to invoke the middleware before invoking the reducer to update the state. This will allow the middleware to potentially replace the action.</p><p>The EchoMiddleware&lt;Action&gt; middleware type is used to return the same Action that is passed into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fdf50a3a4bb2b3d67474b158a5bb869/href">https://medium.com/media/2fdf50a3a4bb2b3d67474b158a5bb869/href</a></iframe><p>This solution now works for a single middleware, but what happens if there are multiple middleware that an application uses. Maybe an application wants a middleware for logging the actions that are executed and some other middleware that handle specific actions to perform asynchronous processing such as invoking web APIs? In this case, we need to be able to define a <em>pipeline</em> of middleware that can execute in order. In the first approach, I can pass an array of Middleware to Store to be executed when dispatch(action:) is called:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0185214579c4e0a0087171e236cdc033/href">https://medium.com/media/0185214579c4e0a0087171e236cdc033/href</a></iframe><p>Now I can use a variadic parameter in the initialer to pass an array of AnyMiddleware&lt;Action&gt; objects to Store to be run in order. This is better because I now have the ability to run multiple middleware, but it’s still problematic. The implementation of dispatch(action:) is more complex and a little harder to understand because of the logic for evaluating the middleware. What would be nice would be to create a wrapper Middleware type that can wrap and execute an array of Middleware. I can create that by creating a new MiddlewarePipeline&lt;Action&gt; type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/808e444dda1a9741b53249ef607b7b3b/href">https://medium.com/media/808e444dda1a9741b53249ef607b7b3b/href</a></iframe><p>The introduction of MiddlewarePipeline&lt;Action&gt; lets me simplify my Store implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/677e87cb82a3cd34d5c4e774e3e74f85/href">https://medium.com/media/677e87cb82a3cd34d5c4e774e3e74f85/href</a></iframe><p>We’re making good progress. This is feeling better. But there’s one more problem: what happens if we want to conditionally enable middleware? We would have to build an array of middleware and then pass it to the Store initializer or dynamically build a MiddlewarePipeline&lt;Action&gt; at runtime. Is there anything we could do to make this simpler?</p><p>When SwiftUI was introduced, the Swift team introduced a new feature called <strong>result builders</strong>. If you have used SwiftUI, you have used result builders. You use a result builder when you define a View. The content that you define in the View is turned into a compile-time function that produces a View that renders text, buttons, or other UI elements on the screen. We can use <strong>result builders</strong> for other things as well, such as for defining a MiddlewarePipeline&lt;Action&gt;. This will allow us to do things such as conditionally enabling middleware, or running a for loop to generate multiple middleware at runtime.</p><p>Building a custom result builder involves defining a struct type and tagging it with the @resultBuilder attribute. You need to define at least one buildBlock method. My first implementation looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ce30190f71b3df54d91f7429bdfbb7/href">https://medium.com/media/02ce30190f71b3df54d91f7429bdfbb7/href</a></iframe><p>This lets me change my Store implementation look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f485ab8f0b2e076598da76e37969d7/href">https://medium.com/media/57f485ab8f0b2e076598da76e37969d7/href</a></iframe><p>This is better, but if you notice from the convenience initializer, the MiddlewareBuilder requires that all of the middleware be converted to AnyMiddleware&lt;Action&gt;. This is not going to be pretty. Fortunately, the result builder gives me another method that can do this conversion for me:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa822c01480a2a8dc281ed143cc082b/href">https://medium.com/media/daa822c01480a2a8dc281ed143cc082b/href</a></iframe><p>The buildExpression method of MiddlewareBuilder will now be called first for each element of the builder function. I can use buildExpression to convert each element to an AnyMiddleware&lt;Action&gt; type, and then the array of all of the middleware can be passed to buildBlock where it will be combined in a MiddlewarePipeline&lt;Action&gt;.</p><p>This further simplifies my Store implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e54b37996c7acef1f0620cda9f1f916e/href">https://medium.com/media/e54b37996c7acef1f0620cda9f1f916e/href</a></iframe><p>Let’s say that I have a LogMiddleware&lt;Action&gt; type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19102e5c1377a5e8bb2bc58f1d6ec529/href">https://medium.com/media/19102e5c1377a5e8bb2bc58f1d6ec529/href</a></iframe><p>With the new implementation, I can create a Store like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b898679d76e51856bd5124e960ae093c/href">https://medium.com/media/b898679d76e51856bd5124e960ae093c/href</a></iframe><p>What happens if I only want to enable the LogMiddleware&lt;Action&gt; in a debug build? This will not work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ac6e9bd9e44387aec6dfa749a9cd19/href">https://medium.com/media/98ac6e9bd9e44387aec6dfa749a9cd19/href</a></iframe><p>However, I can make it work by adding a new construct to my MiddlewareBuilder result builder type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e711ed6ed4c4c500990fdb0303500799/href">https://medium.com/media/e711ed6ed4c4c500990fdb0303500799/href</a></iframe><p>Now the if block will work. When the compiler interprets the body, it will first call buildExpression for the LogMiddleware&lt;Action&gt; item. Then it will call buildBlock to wrap the LogMiddleware&lt;Action&gt; in a MiddlewarePipeline&lt;Action&gt;. Next, the MiddlewarePipeline&lt;Action&gt; will be passed to buildOptional. Finally, buildBlock will be called again to produce the final MiddlewarePipeline. There’s another function that we can implement named buildFinalResult which is called at the end to output the final result of the middleware builder block. This simplifies the MiddlewareBuilder a little:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bc2c2174f1a6c595e13418a69fc8576/href">https://medium.com/media/4bc2c2174f1a6c595e13418a69fc8576/href</a></iframe><p>I next run into an issue if I try to use an if...else block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d40b8712eaa064afc0f80531d9bd983/href">https://medium.com/media/8d40b8712eaa064afc0f80531d9bd983/href</a></iframe><p>To handle the if...else block, we need to implement the buildEither methods on the MiddlewareBuilder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38f57aa81489f1146c3bfc1ee0b2686a/href">https://medium.com/media/38f57aa81489f1146c3bfc1ee0b2686a/href</a></iframe><p>The final case that we’re going to handle is generating multiple middleware in a for block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79bd1bc56025a95b6413b4a71422a61c/href">https://medium.com/media/79bd1bc56025a95b6413b4a71422a61c/href</a></iframe><p>I can handle that by implementing the buildArray function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff7633a89531b2597e75e3fed587e2fb/href">https://medium.com/media/ff7633a89531b2597e75e3fed587e2fb/href</a></iframe><h4>Middleware Use Case</h4><p>Now that we’ve gone through the effort of implementing support for middleware, how would we actually use it? I’ll give an example of logging in. Pretend our demo application prompts the user for a username and password that needs to be sent to an identity service. If the user is authenticated, the identity service issues an access token that can be used to authorize calls to REST APIs.</p><p>For the demo application, my state will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9df5716352aa3c520f027d246df489b2/href">https://medium.com/media/9df5716352aa3c520f027d246df489b2/href</a></iframe><p>I next define two actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e86d432395f494ced2bf7d8b2ff10cd1/href">https://medium.com/media/e86d432395f494ced2bf7d8b2ff10cd1/href</a></iframe><p>The login case takes the username and password as associated values. The setAccessToken case accepts the access token as the associated value.</p><p>I can then create a LoginMiddleware type that will perform the asynchronous login operation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a01ad7cd6b9b6208ce998d4283c84676/href">https://medium.com/media/a01ad7cd6b9b6208ce998d4283c84676/href</a></iframe><p>My application code then looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a29e8e01547268bc77386ea989965e/href">https://medium.com/media/d2a29e8e01547268bc77386ea989965e/href</a></iframe><p>When the Log In button is tapped, the button will dispatch the login(username, password) action to the store. The store will pass the action to the LoginMiddleware which will intercept the action, perform the authentication process asynchronously, and will then forward the access token as a new output action. The setAccessToken(accessToken) action will reach the reducer which will update the application state.</p><p>What if an error occurs during authentication? There is no way to throw an exception using the Middleware. That is actually expected. If you are expecting that an error may occur, you should create an error action that will update the state to report the error. Either way, your middleware should output an action, unless there is nothing to be done from the result of the middleware’s operation, in which case it should return nil to terminate the pipeline.</p><h4>Dispatching Asynchronous Sequences of Actions</h4><p>Another great feature of the new concurrency model in Swift 5.5 is the ability to generate asynchronous sequences using the AsyncSequence protocol. I can extend my Store implementation to allow dispatching actions produced by an asynchronous generator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8315235808dc8257a28f532ad7e7aed2/href">https://medium.com/media/8315235808dc8257a28f532ad7e7aed2/href</a></iframe><h4>Dispatching Actions from Combine Futures</h4><p>What if you have older code that uses Combine’s Future type to implement an asynchronous promise? This framework can handle that too using an extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/104c59eafeda6abc3d8a54774cb1f9f9/href">https://medium.com/media/104c59eafeda6abc3d8a54774cb1f9f9/href</a></iframe><h4>Dispatching Actions from Combine Publishers</h4><p>If we can capture an action from a Combine Future, can we do the same from a Publisher? Yes, we can:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7dd3de30e2fc1f783e53bafe83e5e67/href">https://medium.com/media/e7dd3de30e2fc1f783e53bafe83e5e67/href</a></iframe><h4>Where Have We Gone?</h4><p>In this article, I laid out requirements for a Flux/Redux-like state management store to act as the single source of truth for an application. I designed the state store to also be compatible with SwiftUI and support the use of Combine publishers, ObservableObject, and a @Published state property. I then used the new Swift 5.5 concurrency model to implement the Store as an actor to serialize reads and updates to the application’s state. I next implemented a middleware layer to provide extensibility to my Store and allow for intercepting actions and performing background asynchronous operations for actions, possibly that result in replacing the action with another action. Finally, I extended my Store type to support Combine Future and Publisher types.</p><p>I hope that this journey makes sense to you and you find value in using this Store implementation in your applications.</p><h4>Source Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1103fc9323a70c627281f41b3223011/href">https://medium.com/media/a1103fc9323a70c627281f41b3223011/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525a8879c1be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/managing-swiftui-state-using-redux-525a8879c1be">Managing SwiftUI State Using Redux</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate Azure Static Web App Users Using Azure AD B2C]]></title>
            <link>https://medium.com/neudesic-innovation/authenticate-azure-static-web-app-users-using-azure-ad-b2c-e330369c51bc?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e330369c51bc</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[azure-b2c]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 21:50:55 GMT</pubDate>
            <atom:updated>2022-03-13T14:51:04.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YRngyJS_YTAOn8p6" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hands down, my favorite new Azure feature in quite some time is <a href="https://azure.microsoft.com/en-us/services/app-service/static/">Static Web Apps</a>. Static Web Apps can be free for simple websites or reasonable inexpensive ($9/month) for a few more features. I plan on posting more about Static Web Apps in the future, but in this post I wanted to continue with my Azure Active Directory B2C series and show you how to add user authentication for Static Web Apps using Azure Active Directory B2C and OpenID Connect.</p><p>This is the twelfth post in a series on Azure Active Directory B2C and how to use Azure Active Directory B2C to create an identity management system for a Software-as-a-Service application. If you are new to this series, I recommend reading the earlier posts in the series:</p><ol><li><a href="https://medium.com/neudesic-innovation/building-application-identity-solutions-using-azure-ad-b2c-44a360abc6c9">Building Application Identity Solutions using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/configure-azure-ad-b2c-for-customization-73afa3df45c5">Configure Azure AD B2C For Customization</a></li><li><a href="https://medium.com/neudesic-innovation/understanding-the-b2c-directory-99c680c8da9c">Understanding the B2C Directory</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-or-sign-in-users-with-azure-ad-b2c-part-1-29f8c290b6e7">Sign Up or Sign In Users With Azure AD B2C: Part 1</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-new-users-using-azure-ad-b2c-6477b5df5737">Sign Up New Users Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/log-in-with-local-accounts-on-azure-ad-b2c-57f1f9ba753b">Log In With Local Accounts on Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/combining-sign-up-and-sign-in-into-a-single-policy-using-azure-ad-b2c-a14e79277eae">Combining Sign Up and Sign In Into a Single Policy Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">Using Azure AD B2C to Authenticate Web App Users</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-ios-app-users-ef3f82435f7d">Using Azure AD B2C to Authenticate iOS App Users</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-android-app-users-9506f7a01a17">Using Azure AD B2C to Authenticate Android App Users</a></li><li><a href="https://medium.com/neudesic-innovation/validating-user-passwords-for-azure-ad-b2c-b288687f69ea">Validating User Passwords for Azure AD B2C</a></li></ol><h4>Why Use App Service Authentication with Static Web Apps?</h4><p>In <a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">a previous post</a>, I demonstrated how to use the Microsoft Authentication Library (MSAL) for JavaScript to implement the sign up and log in services for a Vue.js web application. There was another way that I could have implemented authentication, and it is built into Static Web Apps. In fact, it’s built into Static Web App’s parent technology: <a href="https://azure.microsoft.com/en-us/services/app-service/">App Service</a>.</p><p>App Service supports built-in authentication services using identity providers such as Azure Active Directory, Facebook, Google, Twitter, and external OpenID Connect providers. As an application of App Service, apps hosted using Static Web Apps inherit this feature. But why would one choose to use the built-in authentication for a static web app instead of using MSAL like I demonstrated in my earlier article?</p><p>There are a couple of reasons:</p><ol><li>Not every static site is a web application. A static site may hold documentation or downloads that you want to protect to only allow authorized users to reach the files and to download the files or view them in a web browser.</li><li>Static Web Apps can include Azure Functions as part of the application. By using built-in authentication, calls to Azure Functions happen within the context of the security model and Azure Functions can be authorized based on the user’s identity and roles.</li></ol><p>Even for a single page application like a Vue.js application or Angular application, using the built-in authentication may be much easier than having to roll your own wrapper around MSAL.</p><h4>Create a Single Page Application</h4><p>To begin my demonstration, I am going to repeat the process of creating a single page application using the Vue.js framework. I will open a terminal on my laptop and create the application using the <a href="https://cli.vuejs.org/">Vue CLI</a>:</p><pre>vue create helloworld</pre><p>I will then go to GitHub and will create a new repository for my web application. I will copy the Git repository URL and will register it with my application, then I will push the changes up to GItHub:</p><pre>cd helloworld<br>git remote add origin &lt;github-repo-url&gt;<br>git push -u origin main</pre><p>Next, I will create the Static Web App that will host my application:</p><ol><li>Open <a href="https://portal.azure.com/">Azure Portal</a> in a web browser. If necessary, switch to the directory for your Azure subscription (not the directory for your Azure Active Directory B2C tenant).</li><li>Click the <strong>Create a resource</strong> link.</li><li>In the search field, type Static Web App and press Enter or click the search result.</li><li>Click the <strong>Create</strong> button to create a Static Web App resource.</li><li>Select or create a new resource group for the Static Web App resource.</li><li>In the <strong>Name</strong> field, enter a name that you want to use for the Static Web App. The name is not used for the DNS name. You can configure the DNS name later, but a default DNS name will be chosen for you automatically.</li><li>For the <strong>Plan type</strong> field, you will need to choose <strong>Standard</strong>. The free plan for Static Web Apps does not support custom OpenID Connect providers for authentication, so you must go with the paid plan type. The pain plan will cost $9/month.</li><li>For the <strong>Azure Functions and staging details</strong> field, choose the region where you want the functions and web app to be hosted.</li><li>For the <strong>Deployment details</strong> field, choose GitHub.</li><li>Click the <strong>Sign in with GitHub</strong> button.</li><li>In the <strong>Organization</strong> field, choose your GitHub account or an organization that you are a member of.</li><li>In the <strong>Repository</strong> field, choose the repository that you created earlier to host the source code for your web app.</li><li>In the <strong>Branch</strong> field, choose main.</li><li>In the <strong>Build Details</strong> section that appears, choose <strong>Vue.js</strong> for the <strong>Build Presets</strong> drop-down list.</li><li>Use the default (/) for the <strong>App location</strong> field.</li><li>Leave the <strong>Api location</strong> field empty.</li><li>Leave the default (dist) for the <strong>Output location</strong> field.</li><li>Click the <strong>Review + create</strong> button.</li><li>Click the <strong>Create</strong> button to create the Static Web App.</li><li>After the Static Web App is created, go to the new resource. Copy the domain name for the Static Web App and save it. You will need it for the next section.</li></ol><p>When you create the Static Web App, Azure will automatically generate a deployment script that uses GitHub Actions to deploy your web app to the Static Web App host when changes are committed to the main branch. You can check GitHub to see when the workflow completes, or keep refreshing the static web app host until the Vue.js starting homepage appears.</p><h4>Create the App Registration</h4><p>Before we can add authentication to the web application, we need to register the application with Azure Active Directory B2C. In the <a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">earlier post</a>, we only registered the application but did not create a client secret. This was because the application was publicly available to download and a client secret could have been easily compromised. When we use Static Web Apps with built-in authentication, the authentication occurs on the server side between the Static Web Apps instance and the Azure Active Directory B2C tenant, so we will use a client secret in this case to authenticate the host to the Azure Active Directory B2C tenant.</p><ol><li>Open <a href="https://portal.azure.com/">Azure Portal</a> and switch to the directory for the Azure Active Directory B2C tenant.</li><li>Open the Azure Active Directory B2C portal.</li><li>In the left navigation menu, click the <strong>App registrations</strong> link.</li><li>Click the <strong>New registration</strong> link at the top.</li><li>In the <strong>Name</strong> field, enter the display name that you want users to see for your application. This can be changed later.</li><li>In the <strong>Supported account types</strong> field, choose <strong>Accounts in any identity provider or organizational directory</strong>.</li><li>In the <strong>Redirect URI</strong> section, choose <strong>Web</strong> for the platform. For the Redirect URI, enter https://&lt;static-web-app-domain-name&gt;/.auth/login/b2c/callback</li><li>Make sure that <strong>Grant admin content to opened and offline<em>access permissions</em></strong> is checked.</li><li>Click the <strong>Register</strong> button.</li></ol><p>We next need to create the client secret used for server-to-server authentication:</p><ol><li>From the application’s <strong>Overview</strong> page, copy and save the value of the <strong>Application (client) ID</strong> field for the next section.</li><li>Click the <strong>Certificates &amp; secrets</strong> link in the left navigation menu.</li><li>Click the <strong>New client secret</strong> link.</li><li>Enter the name of the web application in the <strong>Description</strong> field.</li><li>Choose an expiration period for the client secret.</li><li>Click the <strong>Add</strong> button.</li><li>Copy the client secret value and save it for the next section.</li></ol><h4>Configure the Static Web App</h4><p>The OAuth/OpenID Connect client identifier and secret values need to be added to the configuration for the Static Web App. These values are never stored in your repository, so you do not need to worry about exposing those values there.</p><p>⚠️ The client secret value could/should be stored in Key Vault. I’m not going to demo that in this article, but you should store the value there. For more information, <a href="https://docs.microsoft.com/en-us/azure/static-web-apps/key-vault-secrets">read this</a>.</p><ol><li>In Azure Portal, switch to the directory for your Azure Subscription.</li><li>Navigate to your Static Web App.</li><li>In the left navigation menu, click <strong>Configuration</strong>.</li><li>Click <strong>Add</strong> and add a setting named B2C_CLIENT_ID and store the application identifier in that value.</li><li>Click <strong>Add</strong> and add a setting named B2C_CLIENT_SECRET and store the secret key in that value.</li><li>Click the <strong>Save</strong> button at the top to save the new configuration settings.</li></ol><p>Next, create a file named staticwebapp.config.json in the root directory of your web application. Copy the following content into staticwebapp.config.json. Be sure to replace the wellKnownopenIdConfiguration value with your Azure Active Directory B2C tenant name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e53695db490c9dba77ef80e9676fb15/href">https://medium.com/media/1e53695db490c9dba77ef80e9676fb15/href</a></iframe><p>This configuration turns off all of the built-in identity providers and defines a new OpenID Connect identity provider using your Azure Active Directory B2C tenant. The configuration requires that all requests be authenticated in order to download any of the web application files. When the user first attempts to connect to your web application, Static Web App will see that the user is unauthenticated and will redirect the user to the /.auth/login/b2c address. This redirect will initiate the OpenID Connect/OAuth 2.0 flow to authenticate the user. After the user authenticates, they will be redirected to /.auth/login/b2c/callback where Static Web App will process the response and extract the ID and access tokens and create the user’s session.</p><p>If you try to authenticate at this point, you will be redirected to Azure Active Directory B2C and can sign in using a username and password or sign up, but the redirect is going to fail. The reason for this is that our Azure Active Directory B2C custom policies do not return all of the information that is needed. If you will recall, I built the custom policies to only do the bare minimum. In order for Azure Active Directory B2C to work, we need to return one additional field in the identity token: the user’s display name. The display name can be present in either the displayName or name field. I will update the custom policies next.</p><h4>Returning the User’s Name</h4><p>I am back looking at my custom policies. I did define the displayName claim and I am initializing it with the user’s username and persisting it to the directory. I could go through all of the work to expose the displayName claim and output it from my relying parties, but I don’t need to do that at this point. Since the displayName and username match, the username is stored in the signInName claim and I can return that directly from the relying party policies and change the name to name or displayName.</p><p>I will start by updating my B2C_1A_SIGNUP policy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff52155eb0c6c5de3d4bf0394e6930a/href">https://medium.com/media/fff52155eb0c6c5de3d4bf0394e6930a/href</a></iframe><p>You will notice that I defined a new &lt;OutputClaim&gt; element referencing the signInName claim. I am outputting the claim with the name name. This &lt;OutputClaim&gt; will cause the name claim to appear in the JWT that is issued by the relying party policy.</p><p>I made the same changes to the B2C_1A_LOGIN and B2C_1A_SIGNUPORLOGIN policies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6a80900436c5fe0633772116816306/href">https://medium.com/media/0d6a80900436c5fe0633772116816306/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4bbb788fbd059dbbbce2369c75389bc/href">https://medium.com/media/a4bbb788fbd059dbbbce2369c75389bc/href</a></iframe><p>Go back to the Azure Portal, switch to the Azure Active Directory B2C directory, and then upload the updated custom policies, making sure to overwrite the earlier versions. Then open up a web browser and attempt to open you web application in the browser. You should be prompted to log in, and once you log in, you will be redirected to your web application.</p><h4>Viewing the User’s Information</h4><p>A web application that is using Static Web App’s built-in authentication service can obtain information about the user and the claims returned from the Azure Active Directory B2C. After you log into your web application, open a JavaScript Console using the Developer Tools for your web browser. Enter the following commands into the console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbcda677699be550f4d0a4bd4ebdb9a/href">https://medium.com/media/3cbcda677699be550f4d0a4bd4ebdb9a/href</a></iframe><p>This will output the array of claims, the identity provider, the user’s unique identifier, and the user’s username if the user is authenticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*616hLPMMvKdxIMm49Lc6Lw.png" /><figcaption>The user information that is available to the web application</figcaption></figure><h4>Where Have We Gone?</h4><p>We now have two ways to use Azure Active Directory B2C to log into a single page web application. We can either use the built-in identity provider support or use the Microsoft Authentication Library for JavaScript. But for non-single page applications, we have also shown how we can use Azure Active Directory B2C to protect any kind of static web content and require user identities to be known.</p><p>:warning: The built-in identity provider is not always the best way to go for authenticating users. If your web app is going to use the built-in Azure Functions support to implement your backend logic, then this approach will work. If your application needs to invoke REST APIs going through Azure’s API Management gateway, you may be better off going with MSAL to get direct access to the access token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e330369c51bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/authenticate-azure-static-web-app-users-using-azure-ad-b2c-e330369c51bc">Authenticate Azure Static Web App Users Using Azure AD B2C</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating User Passwords for Azure AD B2C]]></title>
            <link>https://medium.com/neudesic-innovation/validating-user-passwords-for-azure-ad-b2c-b288687f69ea?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b288687f69ea</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-b2c]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 04:12:10 GMT</pubDate>
            <atom:updated>2022-02-19T04:12:10.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZc8x6yVCEkHB2mH8L-NXg.png" /></figure><p>In this series, I have shown how to create an Azure Active Directory B2C tenant with a basic sign up and log in process using a username and password. I have also shown how to add user authentication to web and mobile applications using the Microsoft Authentication Library. Now I’m going to return back to my custom policies and build those out a bit more to add new features. In this post, I’m going to look at validating passwords using the <a href="https://haveibeenpwned.com/">haveibeenpwned</a> password database.</p><p>This is the eleventh post in a series on Azure Active Directory B2C and how to use Azure Active Directory B2C to create an identity management system for a Software-as-a-Service application. If you are new to this series, I recommend reading the earlier posts in the series:</p><ol><li><a href="https://medium.com/neudesic-innovation/building-application-identity-solutions-using-azure-ad-b2c-44a360abc6c9">Building Application Identity Solutions using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/configure-azure-ad-b2c-for-customization-73afa3df45c5">Configure Azure AD B2C For Customization</a></li><li><a href="https://medium.com/neudesic-innovation/understanding-the-b2c-directory-99c680c8da9c">Understanding the B2C Directory</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-or-sign-in-users-with-azure-ad-b2c-part-1-29f8c290b6e7">Sign Up or Sign In Users With Azure AD B2C: Part 1</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-new-users-using-azure-ad-b2c-6477b5df5737">Sign Up New Users Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/log-in-with-local-accounts-on-azure-ad-b2c-57f1f9ba753b">Log In With Local Accounts on Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/combining-sign-up-and-sign-in-into-a-single-policy-using-azure-ad-b2c-a14e79277eae">Combining Sign Up and Sign In Into a Single Policy Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">Using Azure AD B2C to Authenticate Web App Users</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-ios-app-users-ef3f82435f7d">Using Azure AD B2C to Authenticate iOS App Users</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-android-app-users-9506f7a01a17">Using Azure AD B2C to Authenticate Android App Users</a></li></ol><h4>What is “pwned”?</h4><p>A <em>pwned</em> password is a password that has been compromised or exposed in a data breach. A <em>pwned</em> password does not necessarily mean that one of your accounts was hacked. Sometimes companies or websites accidentally expose data files containing this information and the data file becomes public knowledge. A <em>pwned</em> password is out there though. People know about it. For the purpose of this article, a <em>pwned</em> password is not a password that you want users to be using to log into their account.</p><p>For more information, see the <a href="https://haveibeenpwned.com/FAQs">haveibeenpwned FAQ</a>.</p><h4>How Do We Detect Pwned Passwords?</h4><p>The <strong>Have I Been Pwned</strong> website maintains a database of millions of passwords that have been compromised from public data breaches. Fortunately for our needs, we do not need to download the entire database; instead we will use a freely available API that will allow us to securely query and detect if the password exists in the database.</p><p>I will be implementing the following algorithm:</p><ol><li>The user’s password is captured in the sign up form.</li><li>The custom policy will invoke an Azure Function and will pass the password as input.</li><li>The Azure Function will calculate the SHA-1 hash of the password.</li><li>The first 5 hexadecimal characters (<em>the prefix</em>) from the SHA-1 hash will be sent as a query to the Have I Been Pwned API.</li><li>The Have I Been Pwned API will use the prefix to find matching hashes for the password. The API will return a stream of text with one hash suffix per line and the number of times that password has been found in data breaches, separated by a colon (:).</li><li>I’ll parse the result list into an array of records. The records appear to be returned in sorted order by suffix, so I do not need to sort them myself.</li><li>I’ll use a binary search algorithm to determine if the suffix appears in the list. If the suffix appears, the password is rejected. Otherwise, the password succeeds and is valid.</li></ol><h4>Integrating Password Validation with Azure AD B2C</h4><p>Earlier in this series, we have explored creating custom policies using their XML-based domain language. We described relying party policies that launch user journeys and issue tokens containing identity and authorization data for users. So far, the web UI was provided for us by B2C and we only used services that are a part of B2C to complete the user journeys and relying party policies. However, we’re not just limited to what’s in the Azure Active Directory B2C’s box.</p><p>Azure Active Directory B2C supports a <a href="https://docs.microsoft.com/en-us/azure/active-directory-b2c/restful-technical-profile">REST technical profile</a> that we can use in our user journeys. A technical profile is an action that gets executed during the user journey either to perform an action or validate data. A technical profile is similar to a function in other languages. We can use the REST technical profile to pause the user journey and to make a call to a REST API that lives outside of the Azure Active Directory B2C ecosystem to perform a custom action.</p><p>When implementing custom behavior for an Azure Active Directory B2C, <a href="https://azure.microsoft.com/en-us/services/functions/">Azure Functions</a> are the perfect host. They have a low barrier to entry and can be developed, deployed, and tested quickly. There is no server to configure or create. You just deliver your code and it runs. Azure Functions can also expose HTTP endpoints which makes it really simple to build REST APIs that can be consumed by Azure Active Directory P2C policies.</p><h4>Build the Azure Function</h4><p>I am going to start by building my Azure Function to call the Have I Been Pwned API and determine if the user’s password has been compromised. I chose C# and .NET 6 to implement my Azure Function. My Azure Function will be triggered by incoming HTTP requests and will return an HTTP response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7d41d1c29040f73fcc5d8b2963d1363/href">https://medium.com/media/d7d41d1c29040f73fcc5d8b2963d1363/href</a></iframe><p>My function starts by reading the HTTP request to get the password that needs to be validated. It next uses the SHA-1 algorithm to hash the password and retrieve the 40 character hexadecimal string containing the hash of the password. I extract the 5-character prefix from the hash and use the prefix to query the Have I Been Pwned database. I receive back an array of tuples containing the suffixes and the number of times each password has been compromised. I search through the list to match the password that I have with a password in the list and return the result indicating if the password was found or not.</p><p>The request to my Azure Function will be a simple JSON object containing a password field:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85c7cb6758bbeb8e93b95225afb5024/href">https://medium.com/media/d85c7cb6758bbeb8e93b95225afb5024/href</a></iframe><p>The password is sent in the clear in the body of the text, but the HTTP request will be sent using HTTPS, so the value should be safe from prying eyes. I read the request and deserialize the JSON into a Request object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a198359ceeccae4d35ede2d46cda94/href">https://medium.com/media/f5a198359ceeccae4d35ede2d46cda94/href</a></iframe><p>The next step is to hash the password using the SHA-1 hashing algorithm. SHA-1 will produce a 20-byte value which I then encode as a 40-character hexadecimal string:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/313aadd6dc6950aded153b1d455f6950/href">https://medium.com/media/313aadd6dc6950aded153b1d455f6950/href</a></iframe><p>From the hashed password, I take the first 5 characters to use as the password prefix and I send the prefix to the Have I Been Pwned API to retrieve all of the suffixes that may include the password that I am searching for:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44844f4da3d1c57ca8edb9f73a50d159/href">https://medium.com/media/44844f4da3d1c57ca8edb9f73a50d159/href</a></iframe><p>The Have I Been Pwned API will return a text response with one record per line. The fields are delimited by a colon(:). The first field is the suffix for a matching password with the same prefix. The second field has the number of times that the password has been exposed in data breaches. I parse the result stream and place the values into an array of Tuple objects.</p><p>For the final step, I take the list of Tuple objects and search through them. I extract the suffix from the password hash and use a binary search algorithm to find the suffix in the list (I am making the assumption, which is currently the case, that the suffixes are returned by the Have I Been Pwned API in sorted order):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe94e3704893bc4b67693def68b5190b/href">https://medium.com/media/fe94e3704893bc4b67693def68b5190b/href</a></iframe><p>If the suffix is found in the list, I extract the count from the Tuple. I then send back an error response in the body of an HTTP 409 error response to let Azure Active Directory B2C know that the password validation failed. The error response object is defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ab49b9374f76c1a33bedd10e3597c9/href">https://medium.com/media/46ab49b9374f76c1a33bedd10e3597c9/href</a></iframe><p>If the suffix is not found in the list, I return an HTTP 200 response to let Azure Active Directory B2C know that the password is valid and can be used to identify the user.</p><h4>Test the Function Locally</h4><p>After implementing the password validation function, I ran it locally using the Azure Functions Tools to debug the function and to make sure that it worked. When I ran the Functions host locally, my function was hosted at <a href="http://localhost:7071/api/ValidatePassword.">http://localhost:7071/api/ValidatePassword.</a></p><p>I used an HTTP testing tool (I like <a href="https://paw.cloud/">Paw</a>), I sent a test request to my Azure Function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28cbba76700e0bea0293b2bb387ce361/href">https://medium.com/media/28cbba76700e0bea0293b2bb387ce361/href</a></iframe><p>The Function generated and returned this response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04d4c01d6bd50bb2f3b212635235adb2/href">https://medium.com/media/04d4c01d6bd50bb2f3b212635235adb2/href</a></iframe><p>The error message shows how many times the password has been detected in data breaches.</p><p>When I tested a more difficult password, the password was not found in the list and I received the HTTP 200 response.</p><h4>Host the Azure Function in Azure</h4><p>Now that the Azure Function is built, I need to create a host for it in Azure:</p><ol><li>Open <a href="https://portal.azure.com/">Azure Portal</a> and navigate to the main subscription directory. This is not the directory for the Azure Active Directory B2C tenant.</li><li>Create a new resource and select Function App for the resource type.</li><li>For the <strong>Resource Group</strong> field, I chose an existing resource group that I created earlier in this series to group all of my application’s resources together.</li><li>For the <strong>Function App name</strong> field, this field is used to set the DNS name for your function app, so you will need to choose something unique.</li><li>For the <strong>Publish</strong> field, choose <strong>Code</strong>.</li><li>For the <strong>Runtime stack</strong> field, choose <strong>.NET</strong>.</li><li>For the <strong>Version</strong> field, choose <strong>6</strong>.</li><li>For the <strong>Region</strong> field, choose a region that makes sense for you. I chose <strong>US West 2</strong>.</li><li>Click the <strong>Review + create</strong> button.</li></ol><p>Azure will begin creating the services that will support your Azure Function, including the hosting environment, a storage account, and an Application Insights service for analyzing log data.</p><h4>Publish the Function to Azure</h4><p>Now that the Functions app service has been created in Azure, I can deploy my function to the app. I’m on a MacBook Pro and using <a href="https://www.jetbrains.com/rider/">JetBrains Rider</a> for development. I can publish directly from the IDE. You can also publish to Azure if you are using Visual Studio Code or Visual Studio on Windows.</p><p>Within Rider, I will do the following:</p><ol><li>Right-click on my project. A context menu will appear and I can choose <strong>Publish</strong>. From the drop-down list, I will choose to publish to <strong>Azure</strong>.</li><li>On the <strong>Edit Configuration</strong> screen, I will choose the app that I created in the previous section as the application that I want to publish to.</li><li>I will click on the <strong>Run</strong> button to save the publishing configuration and begin the process of deploying my function to Azure.</li></ol><p>Rider will compile my Function application and will create the ZIP package that will then be uploaded to Azure and deployed in the Functions app service.</p><h4>Register the API Key with Azure AD B2C</h4><p>If you are new to Azure Functions, many times Azure Functions are deployed with authorization enabled. This is done to limit who can call the Azure Function directly. In order to call an Azure Function that requires authorization, callers will need to pass an API key to the function that the Azure Functions app service host can verify. The Azure Function that I defined has authorization enabled.</p><p>To allow Azure Active Directory B2C to invoke the function, I will create a new policy key and will store the API key value in the policy key. I will later reference this policy key when adding the Azure Function call to my custom policy.</p><p>First, I need to get the API key that I can use to invoke the Azure Function:</p><ol><li>Open the Azure Portal and navigate to the Function App.</li><li>In the left navigation menu, click on the <strong>App keys</strong> link.</li><li>Either create a new host key or use the <strong>default</strong> key.</li><li>Click on the <strong>Value</strong> field to show the key.</li><li>Copy the key to the clipboard and save for use in the next step.</li></ol><p>Now that I have the API key, I can create a policy key and store the API key in it:</p><ol><li>Open Azure Portal and switch to the directory for my Azure Active Directory B2C tenant.</li><li>Open the Azure Active Directory B2C console.</li><li>In the left navigation bar, click the <strong>Identity Experience Framework</strong> link.</li><li>In the left navigation bar, click the <strong>Policy keys</strong> link.</li><li>Click the <strong>Add</strong> button.</li><li>In the <strong>Create a key</strong> panel, change the <strong>Options</strong> field to <strong>Manual</strong>.</li><li>In the name, enter a descriptive name like PasswordValidationFunctionKey.</li><li>In the <strong>Secret</strong> field, paste the API key.</li><li>For the <strong>Key Usage</strong> field, set it to <strong>Signature</strong>.</li><li>Click the <strong>Create</strong> button.</li></ol><h4>Invoke the Azure Function from a Technical Profile</h4><p>I am now at the point that I am able to create the technical profile that will invoke my Azure Function to validate passwords, and then to add that technical profile to the sign up flows for my policies. The first thing that I will need to do is to obtain the URL where my Azure Function is hosted:</p><ol><li>Open Azure Portal and switch to your main subscription.</li><li>Navigate to the Function app.</li><li>In the left navigation menu, click the <strong>Functions</strong> link.</li><li>Click on the <strong>ValidatePassword</strong> function in the list of functions (there should be only one if you are following along).</li><li>At the top of the page, click on the <strong>Get Function Url</strong> button. This will display a popup with the URL.</li><li>Copy the main part of the URL. You do not need the query string containing the code.</li></ol><p>⚠️ <strong>NOTE:</strong> I am making the assumption that you have been following along in this series and have custom policies similar to what I have built. If you are doing this with your own policies, you may need to adapt.</p><p>I opened up my custom policy XML files in Visual Studio Code next to create the technical profile. Looking at where I left off, I am going to add the new technical profile to the base.xml file so that it is shared by signup.xml and signup_or_login.xml. At the bottom of the &lt;ClaimsProviders&gt; element, I added a new claim provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db3de3c150db25d7251a415117b3397/href">https://medium.com/media/1db3de3c150db25d7251a415117b3397/href</a></iframe><p>This technical profile implements a REST call to an external web API. The ServiceUrl metadata item contains the URL where the API is hosted. The SendClaimsIn metadata item instructs the REST provider to take the input claims and store them in a JSON blob in the body of the request. The AuthenticationType metadata item instructs the REST provider to read the API key from the B2C_1A_PasswordValidationFunctionKey policy key and pass the API key in the x-functions-key HTTP header of the request.</p><p>The &lt;InputClaims&gt; section will be turned into a simple JSON object and sent in the body of the HTTP request. The new password for the user is stored in the newPassword claim. I will map the newPassword claim to the password claim because the Azure Function looks for the password to validate in the password field in the JSON request.</p><h4>Add Password Validation to Sign Up</h4><p>The final step is to add password validation to the user’s sign up flow. I currently have two sign up flows. The first flow is independent in signup.xml and the second one is combined with the login flow in the signup_or_login.xml policy. Fortunately, I don’t need to modify either of those and I can make the change in the base.xml policy file.</p><p>In base.xml, the sign up for both flows is handled by the ShowSignUpForm technical profile. If I want to validate the password before the user is created, I can add the password validation call as a &lt;ValidationTechnicalProfile&gt;. Validation technical profiles are called when a self-asserted form is submitted to validate the values that were provided by the user, and to actually create the user. I can add the call to the ValidatePassword technical profile immediately before the call to CreateLocalUser, therefore is the password is invalid, the user will not be created.</p><p>In base.xml, I updated the ShowSignUpForm technical profile to invoke the ValidatePassword technical profile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8be5917824fea0e26ed103710a6a7a9c/href">https://medium.com/media/8be5917824fea0e26ed103710a6a7a9c/href</a></iframe><p>Save the changes and upload the new base.xml custom policy to your Azure Active Directory B2C tenant.</p><h4>Test Password Validation</h4><p>I am going to begin by testing the password validation in my sign up custom policy. When I run the custom policy in the Azure Active Directory B2C tenant, I am first taken to my sign up form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRRMgp47zj2yzqoH87fyMQ.png" /><figcaption>The sign up form</figcaption></figure><p>When I enter a username and the password Password1, I receive the error telling me how many times the password has been discovered in a data breach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIYogAVm06GLyGHLErroOw.png" /><figcaption>The error message shows that the password has been compromised 220,490 times</figcaption></figure><p>When I enter a valid password that has not been breached, then my new user account is created.</p><p>When I run the combined sign up or log in policy, I should see the same result when I sign up as a new user.</p><h4>Where Have We Gone?</h4><p>In this article, I have demonstrated how to extend a custom policy in Azure Active Directory B2C using an Azure Function invoked as a REST API. Using the Restful technical profile in Azure Active Directory B2C, we can integrate with other systems or enhance our custom policies and user flows with custom behavior. I have also demonstrated how to use an Azure Function to do data validation of a field, in this case the password for the new user account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b288687f69ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/validating-user-passwords-for-azure-ad-b2c-b288687f69ea">Validating User Passwords for Azure AD B2C</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Azure AD B2C to Authenticate Android App Users]]></title>
            <link>https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-android-app-users-9506f7a01a17?source=rss-4d3e14d1e5d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9506f7a01a17</guid>
            <category><![CDATA[azure-b2c]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Michael Collins]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 14:26:16 GMT</pubDate>
            <atom:updated>2022-02-16T14:26:16.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="This image shows the log in form that is rendered by Azure Active Directory B2C in an Android web view." src="https://cdn-images-1.medium.com/max/1024/1*YMdg-7siMAVphKX-utFDPg.png" /></figure><p>Previously in this series, I have shown how to <a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">authenticate web users</a> and <a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-ios-app-users-ef3f82435f7d">iPhone or iPad users</a>. In this post, I will turn my attention to the Android platform and how to use Azure AD B2C to authenticate the users of an Android app using the <a href="https://github.com/AzureAD/microsoft-authentication-library-for-android">Microsoft Authentication Library for Android</a>.</p><p>This is the tenth post in a series on Azure Active Directory B2C and how to use Azure Active Directory B2C to create an identity management system for a Software-as-a-Service application. If you are new to this series, I recommend reading the earlier posts in the series:</p><ol><li><a href="https://medium.com/neudesic-innovation/building-application-identity-solutions-using-azure-ad-b2c-44a360abc6c9">Building Application Identity Solutions using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/configure-azure-ad-b2c-for-customization-73afa3df45c5">Configure Azure AD B2C For Customization</a></li><li><a href="https://medium.com/neudesic-innovation/understanding-the-b2c-directory-99c680c8da9c">Understanding the B2C Directory</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-or-sign-in-users-with-azure-ad-b2c-part-1-29f8c290b6e7">Sign Up or Sign In Users With Azure AD B2C: Part 1</a></li><li><a href="https://medium.com/neudesic-innovation/sign-up-new-users-using-azure-ad-b2c-6477b5df5737">Sign Up New Users Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/log-in-with-local-accounts-on-azure-ad-b2c-57f1f9ba753b">Log In With Local Accounts on Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/combining-sign-up-and-sign-in-into-a-single-policy-using-azure-ad-b2c-a14e79277eae">Combining Sign Up and Sign In Into a Single Policy Using Azure AD B2C</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-web-app-users-9fee104de8a4">Using Azure AD B2C to Authenticate Web App Users</a></li><li><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-ios-app-users-ef3f82435f7d">Using Azure AD B2C to Authenticate iOS App Users</a></li></ol><h4>Create an Android Application</h4><p>📝 <strong>NOTE:</strong> I am using <a href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a> to do my Android development, but the instructions should also apply to <a href="https://developer.android.com/">Android Studio</a>.</p><p>In the IDE, I created a new Android application. I selected the <strong>Empty Activity</strong> template to create a skeleton app with a starter activity that I can customize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT0UYG8SJEFcUl_8iXA1DA.png" /><figcaption>Select a Project Template view with the Empty Activity template selected</figcaption></figure><p>I chose Kotlin for the implementation language and based on demo on the Android SDK version 29:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xhezP1oGLATKD9plkHYuA.png" /><figcaption>Configuration settings for the new project</figcaption></figure><h4>Add the Microsoft Authentication Library for Android</h4><p>After creating the starter application, I added the dependency on the MSAL library for Android. To do that, I needed to add the MSAL library to the list of dependencies for Gradle, and register the Maven store where Gradle will look for the MSAL library.</p><p>New applications created by the IDE have two build.gradle files that need to be modified. The build.gradle in the root directory of the project is the main configuration for the build system. The app/build.gradle file contains the list of dependencies that are necessary to build the app module that implements the heart of the Android application.</p><p>I started by modifying the root build.gradle file. Inside of the buildscript.repositories property, I added the URL for the Maven repository where the MSAL library can be downloaded from:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eccb2e666f2ad1c0edccfee0d4915f2/href">https://medium.com/media/6eccb2e666f2ad1c0edccfee0d4915f2/href</a></iframe><p>I next added the MSAL library to the app/build.gradle configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f55ba66505f111289b1bae57c901e73e/href">https://medium.com/media/f55ba66505f111289b1bae57c901e73e/href</a></iframe><p>⚠️ The exclude block is in there because without it, I was receiving errors downloading another framework used by the Microsoft Surface Duo SDK. For more information, see <a href="https://github.com/AzureAD/microsoft-authentication-library-for-android/releases/tag/v1.5.0">the release notes for the 1.5.0 release</a>.</p><p>I synchronized Gradle to download the dependencies and I was ready to move forward to the next step.</p><h4>Configure the MSAL Library</h4><p>The next step is to create a JSON configuration file that the MSAL library will use to determine how to operate at runtime. To create the configuration file:</p><ol><li>In the <strong>Project Explorer</strong>, expand the app/src/main/res folder.</li><li>Right click on the res folder and choose <strong>New</strong> —&gt; <strong>Android Resource Directory</strong>.</li><li>In the <strong>New Resource Directory</strong> modal, change the <strong>Resource type</strong> value to <strong>raw</strong>.</li><li>Click the <strong>OK</strong> button to create the directory.</li><li>Right click on the new raw directory and choose <strong>New</strong> —&gt; <strong>File</strong>.</li><li>For the name of the new file, use auth_config_b2c.json.</li></ol><p>My auth_config_b2c.json file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9acd598602955c87e409d1ba23b535d6/href">https://medium.com/media/9acd598602955c87e409d1ba23b535d6/href</a></iframe><p>I replaced the CLIENT-ID value with my application ID from Azure Active Directory B2C. For the HASH value, this can be generated for development by running this command in the terminal:</p><pre>keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64</pre><p>When you are prompted to enter the password for the key store, the default value is android. For the HASH value in the configuration file, you may need to replace = characters with the URL encoded equivalent of %3D.</p><h4>Configure the Application Manifest</h4><p>The next step is to update the application manifest. I needed to add the INTERNET and ACCESS_NETWORK_STATE permissions to the application. I also had to register the com.microsoft.identity.client.BrowserTabActivity activity that is used by MSAL to present the Azure Active Directory B2C UI.</p><p>My ApplicationManifest.xml file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df16a64c35f0c7b1f5341481c3ea269f/href">https://medium.com/media/df16a64c35f0c7b1f5341481c3ea269f/href</a></iframe><p>The HASH value in the path should not be URL encoded. = characters can appear as = and not %3D.</p><h4>Configure the App Registration in Azure</h4><p>The final configuration step is to register the Android application with the App Registration in the Azure Active Directory B2C tenant:</p><ol><li>Open a web browser to the Azure Portal and navigate to the App Registration in the Azure Active Directory B2C portal.</li><li>Click in the <strong>Authentication</strong> link in the navigation list on the left.</li><li>Click the <strong>Add a platform</strong> button.</li><li>Choose the <strong>Android</strong> platform.</li><li>In the <strong>Package name</strong> field, enter the application identifier from the app/build.gradle file.</li><li>In the <strong>Signature hash</strong> field, enter the hash that you previously obtained and used in the earlier configuration steps.</li><li>Click the <strong>Configure</strong> button to save the Android application information.</li></ol><p>Later while testing the user authentication, I ran into a problem where MSAL would fail authentication unless I referenced an API. By default, Azure Active Directory B2C will not issue an OAuth 2.0 access token if there are no APIs that need to be authorized. I created a dummy application and API:</p><ol><li>In the Azure Active Directory B2C portal, navigate to the App Registrations screen.</li><li>Click on the <strong>New registration</strong> link.</li><li>Enter a simple name for the app. I used Project Center API.</li><li>For the <strong>Supported account types</strong> field, I chose <strong>Accounts in this organizational directory only</strong>.</li><li>Ensure that <strong>Grand admin consent to opened and offline<em>access permissions</em></strong> is checked.</li><li>Click the <strong>Register</strong> button to create the app registraton.</li><li>In the app registration screen, click on <strong>Expose an API</strong> in the left navigation menu.</li><li>Click the <strong>Add a scope</strong> link to create a new scope.</li><li>Accept the default value for the application in the next screen.</li><li>On the <strong>Add a scope</strong> form, enter <strong>Files.Read</strong> in the <strong>Scope name</strong> field.</li><li>Add a simple description and admin consent description.</li><li>Ensure that <strong>Enabled</strong> is selected for the state value.</li><li>Click the <strong>Add scope</strong> button to save the scope.</li><li>Navigate back to your app registration (the app, not the API app).</li><li>In the left navigation menu, choose the <strong>API permissions</strong> link.</li><li>Click the <strong>Add permissions</strong> button.</li><li>In the <strong>Request API Permissions</strong> view, change to the <strong>My APIs</strong> tab.</li><li>Select the API application</li><li>Check the <strong>Files.Read</strong> permission.</li><li>Click the <strong>Add permissions</strong> button to save.</li><li>On the <strong>Configured permissions</strong> view, click <strong>Grant admin consent for (app name)</strong> and approve the permissions.</li></ol><h4>Update the Main Activity Layout</h4><p>The configuration is done! It’s time to get to the good stuff. The default application template creates a basic UI for our MainActivity class that displays a hello message in a text field. I will replace the text field with a button that the user can tap to log into the application:</p><ol><li>Open app/src/main/res/layout/activity_main.xml in the IDE.</li><li>Select the text box in the view and delete it.</li><li>Add a Button to the layout and align the button so that it appears in the center of the view.</li><li>Change the text in the button to Log In and change the identifier to logInButton.</li></ol><h4>Implement the Log In Feature</h4><p>Now for the code. Here is my MainActivity.kt file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7123c7e3625f2fac4bd2725c8b15b3/href">https://medium.com/media/df7123c7e3625f2fac4bd2725c8b15b3/href</a></iframe><p>I declare two fields on MainActivity. The msalApplication field stores the reference to the MSAL library’s PublicClientApplication object that I will use to authenticate users. After logging in, the user’s account will be stored in the account field for future use.</p><p>In the onCreate function, I am attaching the logInButton to its event handler and then making it disabled by default. I am then trying to create the PublicClientApplication instance using the createSingleAccountPublicClientApplicationMethod. I am passing the function the reference to the configuration JSON resource that I created earlier. The callback listener uses the onCreated function to store the reference to the PublicClientApplication instance and enable the log in button.</p><p>When the user taps the log in button, the logIn function will be called. logIn will use the msalApplication.signIn function to authenticate the user using MSAL and Azure Active Directory B2C. The web browser will open up and the user will be presented with the Azure Active Directory B2C web UI to log in. When the user has logged in, the listener’s onSuccess function will be called and I can obtain and store the user’s account.</p><h4>Testing the Implementation</h4><p>With the code finally written, I can turn my attention to manual testing. When I run the app in the Android Emulator, I get presented with my MainActivity and I can see the log in button. Initially the log in button is disabled, but it should quickly change to enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1-mTD1LRla7QkpWhqgpNmQ.png" /><figcaption>Main activity showing the log in button</figcaption></figure><p>When I tap the log in button, the web browser opens up and I am taken to the web log in form from Azure Active Directory B2C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*G6IAUWVlRPo006n9VZpY4A.png" /><figcaption>The Azure Active Directory B2C log in form shown in a web view</figcaption></figure><p>After entering my username and password that I established earlier in this series, I am sent back to the application. I can see in the debugger that the onSuccess function is called and I can see the account information and the claims inside. Everything worked!</p><h4>Where Did We Go?</h4><p>In the last three posts, I have shown you how to add user authentication to a single page web application, an iOS application, and an Android application. I may throw in some future posts showing additional application types such as Flutter or doing server-to-server authentication and authorization. But now that we have log in working and three demo apps, I’m going to switch back and start doing some more cool stuff with Azure Active Directory B2C’s custom policies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9506f7a01a17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neudesic-innovation/using-azure-ad-b2c-to-authenticate-android-app-users-9506f7a01a17">Using Azure AD B2C to Authenticate Android App Users</a> was originally published in <a href="https://medium.com/neudesic-innovation">Neudesic Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>