Securing an Azure Static Web App with Auth0 Actions 
Tags: azure, auth0, iam, jamstack
Published: 2021-12-20 11:20:39

---
title: Securing an Azure Static Web App with Auth0 Actions 
published: true
description: An in-depth walkthrough of adding IAM to a Blazor WASM based Azure SWA with Auth0 Actions
tags: Azure, Auth0, IAM, Jamstack
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dorrk8b2w3zd5vszdmdm.png
---

For our 1st code commit, we will initialize a default Blazor WASM application on our local workstation, deploy it on to [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/front-end-frameworks/?WT.mc_id=M365-MVP-5003041), and then secure it with RBAC to verify the IAM is working as intended on the frontend. As the reading time foretells, this is an in-depth and step-by-step code walkthrough of deploying a production-ready app. Buckle up!!!

*Most of the work was done over the release candidate versions, [RC1](https://devblogs.microsoft.com/dotnet/announcing-net-6-release-candidate-1/) & [RC2](https://devblogs.microsoft.com/dotnet/announcing-net-6-release-candidate-2/?WT.mc_id=M365-MVP-5003041), but I have revalidated the codebase against the [LTS version of .net 6](https://devblogs.microsoft.com/dotnet/announcing-net-6/?WT.mc_id=M365-MVP-5003041) released yesterday [11th Nov'21].*

**Canonical reference is on the organization blog: https://www.hackmum.in/blog/azureswa_blazor_auth0_iam**

Also available in a shortened form as a Twitter thread: {% twitter 1471151877840465920 %}

## Local Development

In the past, for services similar to Azure SWA, developers had to follow a circuitous path of building the code on their local machine, followed by deploying it onto the cloud, and only then would they have been able to verify if their code performed as intended — especially true when the feature was infrastructure-dependent, like Identity and Access Management (IAM).


### Azure SWA CLI

Azure SWA addresses the above pain point by providing a command-line tool that approximates the cloud environment: [SWA CLI](https://techcommunity.microsoft.com/t5/apps-on-azure/introducing-the-azure-static-web-apps-cli/ba-p/2257581/?WT.mc_id=M365-MVP-5003041), and we will be relying on its core features to emulate authentication, custom routing, and route authorization.

Install the SWA CLI globally

```javascript
npm install -g @azure/static-web-apps-cli
```

Since our Blazor WASM application will primarily address the organizer use cases, we will name it accordingly.

```dotnet
dotnet new blazorwasm -o OrganizerWeb
```

Ensure you are in the main git branch.

![dotnet new command creating a Blazor WASM project with the terminal logs showing the output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gq0frfl13vjtxckko2tp.png)

Immediately, you are confronted by the bane of modern software development: the spawning of way too many files.

![dotnet new creating too many files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h16z9bh2v5ns2mo8l1f5.png)

Create a .gitignore to ensure the unnecessary files are not inadvertently checked-in.

```dotnet
dotnet new gitignore
```

Please don't forget to check-in the .gitignore file, though🤷‍♂️.
![Cheeky Git commit message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqeszq6voqmamwc8nk5y.png)

While creating the Blazor WASM project, .net will generate settings of application URLs with random ports. It's a matter of preference, but I like to standardize the port numbers [which will help us later when using the SWA CLI].

![launch settings ports](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/37g5iggd6alj90sddxry.png)

Let's kick the tires to ensure things are in working order.

```dotnet
dotnet watch
```

We also get to see in action one of the most touted features of .net 6: [hot reload](https://devblogs.microsoft.com/dotnet/introducing-net-hot-reload/?WT.mc_id=M365-MVP-5003041), which also generated a lot of [heat](https://devblogs.microsoft.com/dotnet/net-hot-reload-support-via-cli/?WT.mc_id=M365-MVP-5003041)🔥 recently

![Running .net watch command for hot reload](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gaggmrmluj1chyny1o1q.png)

Looks good.

![Running .net watch  the weather forecast page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9esxtglgz7gkc6kerge.png)

Next up, we want the Azure SWA CLI to serve the Blazor WASM application. I prefer to execute the SWA commands at the solution level because it provides a vantage position for when we want to repeat this later when including the Azure Functions project(s).

```javascript
swa start http://localhost:5000 --run "cd OrganizerWeb && dotnet watch run"
```

Voilà, the Blazor WASM served from the SWA CLI!!!

![Azure SWA CLI terminal logs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lnwlcjsk25gsdjfu78y9.png)

A page automatically opens in your browser, but that is powered by the .net watch command[please close this tab/browser; lest it will confuse you during development]. Note the URL with the port number 4280 and traverse to that location; this is the Azure SWA CLI rendered page.

![Default weather app served with Azure SWA CLI port number highlighted in the location bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lal35zxwzlc99zom5sl8.png)

### SSL

Production web apps are served over HTTPS. Moreover, the default security posture adopted by browsers is to only open SSL-secured sites. Case in point, when I ran the watch run command above, .net opened the browser in https[port 7001] without a hitch. But traversing to the SWA CLI rendered page, which is being served over the ol' plain HTTP, the browser promptly disallowed it.

![Browser page displayed with the message of insecure connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av90a6dw7bfxy7bcu80v.png)

Using SSL right from the get-go ensures we catch any potential bugs related to it early. Unfortunately, [SWA CLI repository's README](https://github.com/azure/static-web-apps-cli) skimps on the details.

- One CLI SSL option errored out.
   ![SWA CLI SSL option fail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0lv14h1thbsfhsp0ztz3.png)

- Providing only the SSL option to the CLI ain't cutting it.
  ![SWA CLI option SSL fails with a message to provide key and cert](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzj7sfe2u0wsrdptc4lm.png)

What worked? A certificate and key generated by a Root Certificate Authority, trusted by the browser. I recommend [mkcert](https://web.dev/how-to-use-local-https/#running-your-site-locally-with-https:-other-options) for its ease of accomplishing this. Please ensure that the generated certificate, and key, are kept in a secure location. These should NOT be **checked-in** if generated within the repository folder; if you do so, amend the .gitignore file to exclude the key and certificate files.
  
```javascript
swa start --ssl --ssl-cert="../localhost.pem" --ssl-key="../localhost-key.pem" https://localhost:7001 --run "cd OrganizerWeb && dotnet watch run"
```

To confirm in the terminal logs, note the HTTPS protocol of the SWA CLI rendered URL.

![SWA CLI terminal logs with hot reload, and SSL-enabled URL highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06f8593g60nj38pvzai5.jpg)

Traversing to the URL 👇

![SWA rendered page with SSL lock icon clicked in the browser's location bar, revealing secure connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0u0bswqbpouxryf4gvs.png)

## Azure SWA VS Code Extension

Now it is time to lob our app into the cloud. And we can do it right from the comforts of VS code itself, courtesy of the [Azure SWA extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurestaticwebapps/?WT.mc_id=M365-MVP-5003041).

**Ensure you have checked in all your code and have pushed them up to GitHub.**

Assuming you have validated both your Azure & GitHub profile by the Azure SWA extension:

1. When clicking on the "plus" icon [circled in red below] of the extension, you will be prompted to select the Azure subscription, followed by a dialog box for entering the name of the Azure Static Web App project.
  ![Azure SWA extension with the plus icon circled in red](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztwbgpd8f263bn5nu7kt.png)

2. You will be asked for the Azure Region you wish to deploy the app. Right now, East Asia will be the nearest for the alpha users of the app.
  ![Azure SWA extension dialogue box with a dropdown displaying Azure regions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sv72hvwnm60s2d2ecy2m.png)

3. Your frontend framework: choosing Blazor for this project.
  ![Azure SWA extension dialogue box with a dropdown displaying different frontend frameworks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vub1177cp835itqi7s4y.png)

4. Next, you will be asked for the source folder for your frontend project.
   ![Azure SWA extension dialogue box with a textbox filled with the source folder location](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqy186fchecnf1u6amdx.png)

5. Finally, the build location for your frontend project.
  ![Azure SWA extension dialogue box with a textbox filled with the build location](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gotv2p3z5u3n8680eao1.png)

If everything goes to plan, a VS Code toast notification about the successful completion of the GitHub actions will pop up. And within the Azure SWA extension, and tucked under the subscription it was created in, the Azure SWA project should be listed.

![Azure SWA extension with Azure SWA listed under the subscription it was created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxgjn24qds4rce7z1y6n.png)

By right-clicking on the Azure SWA project, you will be presented with a context menu with one of the menu item called "Browse site". Clicking on it, you can traverse to your Azure SWA hosted page.

🎉🎉🎉 Congratulations! You have successfully deployed your Blazor WASM app to Azure Static Web Apps. 🎉🎉🎉
![Azure SWA context menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrie52asd9nm6mqxdtvz.png)

### Things that tripped me

1. For folks from a TDD/BDD background who would usually begin by creating an Azure SWA project first and then proceed to code, unfortunately, the extension does not work on an empty folder.
  ![VS Code toast notification of error message of empty workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5r52j1auto0z58pke148.png)

2. Having said that, try to deploy your code asap. This project is not just our first project in Azure but also a re-entry into .net [coming from a 10-year Node.js background]. Tinkering with the generated gitignore, I un-commented the below line [brain freeze on my part that I want to attribute to working with ASP pre-2012😉].
  ![wwwroot entry in gitignore](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t319bk095s5c6tf4pk7a.png)
This led to an insidious error: the app worked fine on the local machine via SWA CLI, but on pushing the commits onto the cloud, GitHub actions failed because it could not find those files.

3. When you are creating a new Azure Static Web Apps project, the Azure SWA-generated GitHub action expects the artifacts to be on the default branch[main/master]. I had issues getting to work if I started with other git branches.
  ![Azure SWA GitHub action fail by running on default Git branch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s17wxjcqmhsso87tzk3l.png)
However, once the Azure SWA is created, the GitHub action works very well with other branches in powerful ways, which we will see in "***action***" during our next section.

## Authentication with pre-configured providers

Moving forward, like any good self-respecting production web app out there, our app will have certain pages that needs to be accessed only by authenticated users with authorized roles.

But before plunging headlong into the custom authentication, we will first ensure the IAM plumbing works with one of the Azure SWA pre-configured providers, GitHub.

Let's create a new git branch

```git
git switch -c CustomAuth
```

[Microsoft Learn](https://docs.microsoft.com/en-us/shows/Azure-Tips-and-Tricks-Static-Web-Apps/?WT.mc_id=AZ-MVP-5003041) has a great video series on Azure SWA, and one of them, [Frank Boucher's authentication video](https://docs.microsoft.com/en-us/shows/azure-tips-and-tricks-static-web-apps/how-to-add-a-c-api-to-your-blazor-web-app-12-of-16--azure-tips-and-tricks-static-web-apps/?WT.mc_id=AZ-MVP-5003041), was crucial for this post.

1. Microsoft has released a .net library that configures an Authentication State Provider for our Azure SWA app.[ Don't go by its nomenclature. Microsoft is underselling it; it's not just for Azure Functions😉]

    ```dotnet
    dotnet add package Microsoft.Azure.Functions.Authentication.WebAssembly --prerelease
    ```

    While developing this app in RC1 and RC2, there was only a prerelease version for use. I expected that we would have an official one when .net 6 was released. Alas, it is still in prerelease.
  ![VS Code terminal showing dotnet add package failing with a request to use prerelease version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxj12igwfws6tfz66193.png)

    Also, this package's [nuget](https://www.nuget.org/packages/Microsoft.Azure.Functions.Authentication.WebAssembly/1.0.1-preview) page is bereft of any content for a potential user, and I have serious doubts about the [GitHub repo](https://github.com/Azure/azure-app-service-authentication) it's claiming to be its source.

2. Once you add the library, we need to register the service in the WASM app builder found in the Program CSharp file: the 2 new lines added 👇 [The structure of this page will be different if you are on .net 5.]
   ![Program.cs with horizontal green markers at the start of the new lines added to the file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yt23za25vogzpr0xbk5.png)

3. Next up, we need to bolt on the Authorization scaffolding to the Blazor App [This step is applicable for any Blazor WASM standalone app; it's not specific to Azure SWA]
    ![Blazor WASM's app razor page with code added for authentication highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5z0iwixqxbthavyn416d.png)

    Productivity tip: Use VS Code Format Document to get your code in this file to be indented automatically.
    ![VS Code Command Palette dropdown with Format Document as the first option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cc0qyuxf015xnpk0ozy.png)

4. Let's update the layout of the Weather App by replacing the "About" link with a "Login/Logout" one.
    ![Pre and post of the main layout page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjd1rbpbrm2jwg1605qp.png)

    Check out the URL highlighted within red: **"Azure Static Web Apps uses the [/.auth system folder](https://docs.microsoft.com/en-us/azure/static-web-apps/authentication-authorization/?WT.mc_id=AZ-MVP-5003041&tabs=invitations#system-folder) to provide access to authorization-related APIs."**

5. Run the SWA CLI command to bring up the Azure SWA app locally. When you click the Login link, you will come across one of the best features of SWA CLI: its emulation of the Azure SWA authentication infrastructure.
    ![SWA CLI emulation of Azure SWA authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rehfu9hjnetxlzsy76tj.png)
    The provider is pre-filled with the one we have in our path in the .auth link above, with a text box for the user name and a text area for Roles[for now, we leave it untouched]. Clicking on the Login button will lead you back to the index page with the Login link replaced with a message welcoming the username entered in the emulator page and a **logout** link.
    ![Azure SWA app's index page with the user name highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q45fs4zvspnrvn7uuhx2.png)

6. Presently, anyone can access the Weather Forecast page [reachable at the /fetchdata route].

    ![Weather Forecast page with the Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2xg9f3jech049aidziw.png)

    Let's change that. Adding just two lines in your FetchDate.razor file and a restart should make that happen.

    ![FetchData.razor file with the code addition highlighted in green](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgurx84j5oj05h8po40n.png)

    Now, when an unauthenticated user clicks on the Fetch Data link in the navbar, the page will display a terse message instead of the weather forecast. "Note to self: It would be cool if the famous MC Hammer  **[U can't touch this](https://www.youtube.com/watch?v=otCpCn0l4Wo)** gif plays when an un-authenticated user clicks that link."

    ![Weather Forecast page displaying "Not Authorized" message which is highlighted in red](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wke1ydjwf48k62c3bkrn.png)

7. Hey, wait a minute, even John Smith from earlier can access the Weather Forecast page?!! Quite right, and here's the thing with "[attribute [Authorize]](https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?WT.mc_id=AZ-MVP-5003041&view=aspnetcore-6.0#authorize-attribute)" as it is, it only restricts anonymous access; once you are authenticated(doesn't matter as who), you are through.

    ![The weather forecast is displayed with John Smith as logged in user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9f65hcm8idqounz61hh.png)

    So let's ensure only weather reporters can access the forecast page; we are now introducing Role-based Access Control[RBAC]. It requires a mere amendment to the Authorize Attribute.
    ![fetch data code with Authorize attribute amended with weather-reporter role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pob0lzk2la3hm8xzle7j.png)

    And now, our authenticated but not having the requisite role aka unauthorized user cannot access the forecast page.
    ![Weather Forecast page displays a message of "Not authorized" with John Smith as the logged in user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q49conmr8iwbcw7m542j.png)

    #TIL: David Letterman started his career as a weather reporter in the 70's.
    ![David Letterman in front of weather map](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0323d1udjwszx88n3rdw.png)

    So let's log out and then click on the Login link again to bring us back to the emulator. Only this time, we masquerade as David Letterman in the role of a weather reporter.
    ![Azure SWA CLI emulator with username as David Letterman and role as weather-reporter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzbphbpnzlo0j0rd0z8z.png)

    And lo and behold, David Letterman can access the weather forecast.
    ![Weather Forecast page successfully displayed with David Letterman highlighted in green](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfwr0xwf81w2zctyte2s.png)

The combination of SWA CLI and Azure SWA VS Code extensions is a great way to get started with Azure SWA on your local machine. But it does not mean you can develop the app without an internet connection. The VS Code extension has to connect to the Azure infrastructure to do its job. But also the SWA CLI authentication emulator when using it for the first time since it needs to download a few static assets for the page.
![SWA CLI emulator page along with Developer Tools console showing ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yumz3csqovote2yvegwj.png)

### Pull Request in Pre-Production

Great, now that we have corroborated on the workstation that the web app has a functioning IAM; let's validate it after deploying it on Azure.

Push the branch to GitHub.

```git
git push -u origin CustomAuth
```

The GitHub dashboard for the project displays a helpful message about a git branch being available and persuading us to undertake a Pull Request.

![GitHub project dashboard with pull request button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lii0lii9501ggze1d1v.png)

And like any good OSS project, we follow this hygiene for merging a code into an upstream or main branch.
![GitHub pull request page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9dhrtvnkmlkjgjyc2d54.png)

Remember the GitHub Actions generated for a newly created Azure SWA? It also gets triggered for any Pull Request on the main branch.
![GitHub actions running on pull request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vhj6ci7v0mcojmfhu07m.png)

And here's a crucial productivity feature of Azure SWA: at the end of the successful processing of the GitHub action, the code will be available at a dedicated Stage URL. The Stage URL is almost identical to the production[main/master] branch URL, except for the subdomain appended with the GitHub Pull Request Number and Azure region.
![GitHub Pull Request Page showing the automated comment with the stage URL. The Pull Request on the page is highlighted, and so too is the Stage URL in the comments](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y34zeonuc1ek6x7xrnaw.png)

You can test your stage URL independently or make a side-by-side comparison with the production branch.
![Two browser tabs resized to fit screen side by side for comparison of the production branch and the Stage branch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzy842vopj34g9d0wxfv.png)

Click on the login link[only available in codebase version hosted on the stage URL], and immediately you realize the training wheels are off when the browser redirects to the GitHub Sign-in page.
![GitHub Sign-in page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tolxmqcxagc8fdnc2stb.png)

If you logged in for the first time, you need to consent for your personal information[email &/or username, depending on the provider] being shared with the app.
![Azure consent page when visiting the site for the first time](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jaaatqp1qm1hw96fttc3.png)

We have been authenticated, but we do not yet have access to the Weather Forecast page.
![Weather Forecast page on stage with username highlighted in green and the page message of "Unauthorized access" highlighted in red](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sh9ln4z7p0ql8rh1iphi.png)

Why? David was doing a standup job as a weather reporter, BUT only on my local workstation [SWA CLI]. Over on the stage URL, it's my GitHub profile that is getting authenticated, which has not been assigned any role on the Azure Portal. Anyway, David has a flourishing career as a late-night TV host, and it is time we bid him adieu and have me, or to be precise, my GitHub profile, take over his weather reporting duties on the deployed app. Head on over to the Azure portal and visit the Role management page.

>Can you grasp the significance of the last statement? We created an Azure SWA app, developed it locally, deployed it on Azure, created another branch to incorporate the IAM feature, hosted that version on its own stage URL — we did ALL that and did not have to visit the Azure Portal even once, till now. All accomplished from the comforts of the tools you are most familiar with: VS Code and GitHub. A remarkable win for developer productivity.

Azure SWA provides a built-in [invitation system](https://docs.microsoft.com/en-us/azure/static-web-apps/authentication-authorization/?WT.mc_id=M365-MVP-5003041&tabs=invitations#role-management) to assign roles to users when using pre-approved providers.
![Azure SWA Role invitation tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6hlflc31sfzkdjc7cml.png)

Oops, it looks like we need to revisit our code. Roles in Azure cannot contain hyphens. Replace the old role with ***weathercaster***.
![Role in Authorize attribute changed to weathercaster in Fetch data razor page ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23rm5q5ugs8xq55aod61.png)

Test it locally, as we had done earlier.
![SWA CLI authentication emulator page with the username filled with Github Profile name and weathercaster added to the list of roles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gu5016lh7hrwv6vhgtdr.png)

Looks good.
![Weather Forecast page with username as GitHub profile name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvaibpnpqfdfexxyxa3o.png)

Add the *weathercaster* role to my GitHub Profile name in the Azure Portal. And click on the invitation link generated below, which will redirect you to the main branch version of the web app[You can close this browser tab].
![Role Management page in Azure Portal with weathercaster entered in the role text area](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2n7dgkpf98vovh7p4ue.png)

Push the changes to GitHub. Doing so will once again trigger the GitHub Actions, and at the end of its successful processing, it will generate a new comment with the same Stage URL.
![Visage GitHub Actions page with Azure SWA comments with stage URL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6700wm8jfvsknjf8o3ig.png)

Yay, my Github profile finally has access to the Weather Forecast page.
![Weather Forecast page on the Stage URL with GitHub user profile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8lyd7flav8lv50c5h1n.png)

## Configuration

You can control aspects of the Azure SWA via a JSON configuration file named [staticwebapp.config.json](https://docs.microsoft.com/en-us/azure/static-web-apps/configuration/?WT.mc_id=M365-MVP-5003041). I like to create this file at the root of the Blazor WASM project.

![VS Code Explorer showing location of staticwebapp json within the solution hierarchy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfk30p6s43brtkdshvdq.png)

### Custom Routing

It's a good practice the login link has no reference to the authentication provider involved. And since we do not intend to use the other pre-configured providers[Twitter & Azure Active Directory], it's prudent from a security standpoint to have them disabled.

```json
{
  "routes": [
    {
      "route": "/login",
      "rewrite": "/.auth/login/github"
    },
    {
      "route": "/.auth/login/twitter",
      "statusCode": 404
    },
    {
        "route": "/.auth/login/aad",
        "statusCode": 404
    },
    
    {
      "route": "/logout",
      "redirect": "/.auth/logout?post_logout_redirect_uri=/"
    }
  ]
}
```

Startup the SWA CLI and replace the .auth links in MainLayout accordingly. You can see the hot reload in action too.
![Main layout with custom routes highlighted in red](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5ortwojj451mu1oor4g.png)

Verify the change on your browser's dev tools.
![SWA CLI rendered page with Edge Dev Tools opened and the Login link element's href attribute highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kqlkvorhhwtromtj5ft.png)

Clicking on the Login link should bring you to the SWA CLI emulator. Rinse & repeat.

### Secure Routes by Roles

To be consistent with our code, we have to ensure that a direct request to the server for /fetchdata route of the Weather Forecast page is accessed only by authenticated users with the ***weathercaster*** role.

```json
{
        "route": "/fetchdata",
        "allowedRoles": ["weathercaster"]
}
```

But, there's a caveat. Suppose we allow only folks with the role of "LordCount" to access the /counter route.

```json
{
        "route": "/counter",
        "allowedRoles": ["LordCount"]
}
```

If there is an anonymous direct request to this route, then the platform will not serve the request.
![SWA CLI emulator rendered a 401 page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9jiue1bvrray7cu4yl5.png)

But this does not prevent folks from accessing the route if the first request is to the index file [which is open to anonymous access]. It, in turn, ensures the whole WASM app gets loaded onto the user browser, and now anyone, including the unauthenticated, can access the counter page. [WhyY? The nature of the beast!!! Once a Single Page Application[SPA] is loaded onto the browser, the routes are traversed locally without invoking the Azure infrastructure]. And, unlike the fetchdata page, we have not secured the counter page via the Blazor Authorization implementation.
![Counter page accessed with a Login link showing that page is open to anonymous access](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9jiue1bvrray7cu4yl5.png)

### Fallback Routes

And because it's a SPA, we also need to serve those requests asked of the server for a route that does not adhere to any of the [routing rules](https://docs.microsoft.com/en-us/azure/static-web-apps/configuration#fallback-routes/?WT.mc_id=M365-MVP-5003041). [just like a default statement in a switch clause 😁]

```json
"navigationFallback": {
      "rewrite": "/index.html"
  }
```

We will be revisiting this file as we implement more features in the coming weeks. It is worth your while to familiarize yourself thoroughly with different aspects of the config file. During my research, I found that one of the reasons that the CSP for the global header was somewhat lax was because of [the browser refresh feature](https://github.com/dotnet/aspnetcore/issues/34428#issuecomment-934348957), which, coincidentally I raised just before the meltdown caused by the Hot Reload announcement.
![Dev Tools console showing the CSP error flagged by the browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjifr0z076kedd1fy2hx.jpg)

## Custom Authentication

Now we need to replace GitHub with our custom authentication provider, Auth0. A question might be swirling up in your mind: if the plan was to have Auth0 as our authentication provider, why was I messing around with GitHub? Here's the rub, custom authentication is not part of the Free plan for Azure Static Web Apps but that of the paid [Standard Plan](https://azure.microsoft.com/en-us/pricing/details/app-service/static/?WT.mc_id=M365-MVP-5003041). Our strategy was to ensure we got the nuts and bolts of our frontend's IAM right, without incurring any costs.

Getting custom authentication to work involves a delicate dance amongst the three amigos: Azure SWA[portal + configuration file], Blazor WASM, and Auth0

### Auth0

 [Aaron Powell's post](https://techcommunity.microsoft.com/t5/apps-on-azure-blog/using-auth0-with-static-web-apps/ba-p/2353653/?WT.mc_id=M365-MVP-5003041) has been a big help in configuring the Auth0 part.

1. Create an application, and note the following properties which we will need later on:
   a. Client ID
   b. Client Secret
   c. Domain Authority URL
   ![Auth0 Application Properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjifr0z076kedd1fy2hx.jpg)

2. As OIDC authentication rides piggyback on [OAuth2 authorization flow](https://auth0.com/docs/authorization/protocols/protocol-oauth2), we have to configure the endpoints that Auth0 needs to redirect post the login process.
   ![Auth0 OAuth2 Endpoints](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdlo7h8p8w1k4qjwg6n7.png)

### Azure Portal

1. Visit the Hosting Plan tab under the Static Web App in the Azure Portal to convert the plan from free to standard.
![Hosting Plan of the Azure Static Web App showing the features of both the Free and Standard Plan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91x2oxzy7pilqg78nl33.png)

2. Click on the Configuration link within the navigation pane, choose the stage environment and add two applications secrets, namely AUTH0_CLIENT_ID, & AUTH0_CLIENT_SECRET, with the values from step 1 of the Auth0 subsection above.
![Azure SWA Configuration page with the secrets added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufqufzmpfwo1jnw3uw2p.png)

### Azure SWA Configuration

Back to our code, we provision [custom authentication](https://docs.microsoft.com/en-us/azure/static-web-apps/authentication-custom?WT.mc_id=AZ-MVP-5003041&tabs=openid-connect) in our static web app config file.

```json

{
  "auth": {
    "identityProviders": {
      "customOpenIdConnectProviders": {
        "auth0": {
          "registration": {
            "clientIdSettingName": "AUTH0_CLIENT_ID",
            "clientCredential": {
              "clientSecretSettingName": "AUTH0_CLIENT_SECRET"
            },
            "openIdConnectConfiguration": {
              "wellKnownOpenIdConfiguration": "https://developerday-ind.us.auth0.com/.well-known/openid-configuration"
            }
          },
          "login": {
            "nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
            "scopes": [],
            "loginParameterNames": []
          }
        }
      }
    }
  }
}
```

Three things of note:

1. Named our custom provider as auth0.
  
2. The application secrets we provisioned in the settings on the portal above.
  
3. The well-known OpenID configuration endpoint, available at the Domain Authority URL.

Unfortunately, the Domain Authority URL was not considered sensitive enough to be secured as an application secret. And since we have to check in the code into a public GitHub repository, in the interim, I'm constrained to utilize an Auth0 developer tenant. [Tooting a bit of my own horn: This tenant was employed in the [Auth0 hackathon in which I was runner-up](https://auth0.com/blog/auth0-announces-the-winners-of-the-actions-hackathon/): Used Auth0 Actions with Yoonik Face Recognition; I'll be expanding on this in the upcoming posts]

Also, we need to update the login route in the static file. And because we have implemented this route rule earlier, we don't need to modify the link within the MainLayout page.

```json
{
      "route": "/login",
      "rewrite": "/.auth/login/auth0"
}
```

As we did with the other pre-configured providers, it's now time to thank GitHub for its service and disable it.

```json
    {
      "route": "/.auth/login/github",
      "statusCode": 404
    }
```

Restart the CLI, and once you click on the Login link, the SWA CLI authentication emulator page comes up. We now see the provider field pre-populated with auth0 [the name we gave in the static config file], and I'm using my username as it is in the Auth0 tenant.
![SWA CLI render emulator page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bby2qauckrhizvsk0c5u.png)

By now, you know the drill. Send up the git commits to GitHub and wait for the GitHub actions to complete. Once done, my Auth0 profile can haz some of that sweet Weather Forecast.
![Weather forecast with the Auth0 username highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgcwx2bdgnp1y383qmgv.png)

### Custom Authorization

Update [13th Dec'21]: This section should have been the logical culmination of this blog post. Alas, I am encountering HTTP 500 errors on Azure SWA when incorporating this feature.
![Azure SWA displaying a message about internal server error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqtle36u3gckqe38lur3.png)

There are no logs available to dig through to find the cause, which was compounded by the [total lack of response](https://twitter.com/hackmum/status/1467948077096988672) from the Azure team to our queries for days.

Since they are stakeholders waiting on this and the upcoming blog posts, I could not interminably wait on the Azure SWA team. To get the caravan going, I decided to:

- Create another git branch that will retrace the app a step back on production to the pre-approved providers feature
- Revert to the Free Plan. After all, we bumped up to the paid Standard Plan to have Custom Authentication, and since that is not working, it makes no sense to keep the meter running on the paid plan.
- Update this subsection after a solution from the Azure SWA team.

### Auth0 Role Management

1. On the Auth0 end, we create a Role named "weathercaster"
   ![Auth0 Add Role section with the name and description fields filled out](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syy8hp2dc7iidpe5zpwv.png)

2. Add my username to the role.
    ![Auth0 add the user to the role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrvcezhj7wr5n3i0ycqm.png)

### Auth0 Actions

We need to add the roles to the id token, and just for good measure, I'm also going to add them to the access token. In the past, for my older Auth0 tenants, this was achieved by [Auth0 Rules](https://auth0.com/docs/rules) and later by [Auth0 Hooks](https://auth0.com/docs/hooks). Last year, Auth0 introduced [Actions](https://auth0.com/docs/actions/actions-overview) to supersede them, and it's time we take the new hotness for a ride.

1. We are going to need a Custom Action
    ![Auth0 Action Library](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16njo23ftkswitquddqp.png)

2. Create a Custom Action
    ![Create Auth0 Action Modal Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74ai79cl8ubpwqykgviy.png)

3. The [Monaco code editor](https://microsoft.github.io/monaco-editor/) opens up. And if you get a sense of déjà vu, that's because its also the one for VS Code. Adding a role to an OAuth2.0 token is such a common use case that you can find a code snippet for it, amongst others, after clicking the ***[View Samples](https://auth0.com/docs/actions/triggers/post-login)*** sticky button at the bottom right of the editor, which like the genius developer I am, have already copy-pasted into the editor.
   ![Auth0 Action Code Editor with code snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2s33xoglpexr31or7u80.png)

4. We need to add the roles during our Login Flow.
    ![Auth0 Action Flow Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49qa02nksynp9boprzk1.png)

5. Drag and drop our Custom Action into the Login Flow.
    ![Auth0 Action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l865fkbc9df8w2mspprj.png)

6. Apply the changes, and we are done on the Auth0 end.
    ![Auth0 Action Applied](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04wjd7tqng4lmlyc388o.png)

7. **"Trust, but verify"**: We used the [Auth0 vanilla JS SPA sample](https://auth0.com/docs/quickstart/spa/vanillajs#read-the-user-profile) to check that the Auth0 Action is indeed adding the roles to the ID Token.
   ![Browser page showing the profile sent by Auth0, with the dev tools console also showing the same](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifhkfvinht8njjsmj4mp.png)
  
### Azure Function in Role Management

To glean out the custom roles from the response sent by an identity provider post-authentication, [Azure SWA has a preview feature of using Azure Function to process the payload from the identity provider](https://docs.microsoft.com/en-us/azure/static-web-apps/authentication-authorization??WT.mc_id=M365-MVP-5003041&tabs=function).

In the static config file, we need to enhance the auth section with the path of the Azure Function.

```json

{
  "auth": {
    "rolesSource": "/api/GetRoles",
    "identityProviders": {
      // ...
    }
  }
}

```

But here is where things get awry. For our first iteration of the Azure Function, I wanted to play safe and used the [sample tutorial](https://docs.microsoft.com/en-us/azure/static-web-apps/assign-roles-microsoft-graph?WT.mc_id=M365-MVP-5003041). It's not even processing the payload, but rather hardcoding the result.

![VS Code Editor with left pane showing the API code, right pane the result of the invocation of the function, and the bottom terminal with the command to start the function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohhbceddl4ovmtam49yn.png)

But pushing these changes to GitHub, and post a successful login [verified via Auth0 logs] on the Stage URL, Azure SWA throws up the dreaded internal server error.

## Conclusion

Security is one of the pillars of a well-architected web application. And in my experience, it is always better to tackle it upfront because you have to depend on the ecosystem to get the job done. And if things go wrong, as it panned out here, you have slack in your project timeline to hustle up a Plan B.

Azure SWA is a productivity win for developers but so long as you use one of the pre-configured identity providers. For Custom Authentication, it's not yet ready for prime time.