-->
Microsoft released the swa cli a while ago and this tool makes it trivial to create, test and deploy static web apps to Azure. One question I had was how this would work for local testing and debugging. I recently had the chance to take a look and was impressed with the results.
When we run the app locally using the swa cli we are given the ability to emulate authentication and authorization, this is described here.
Lets give it a try.
I created a simple app with HTML and vanilla JavaScript; this can be seen in github here.
There are a few providers we can use to log in but I am going to use Microsoft Entra which was previously named Azure Active Directory. The html below shows a login and logout button with hrefs that will be handled by the swa cli locally and or Azure when deployed.
<li><a href="/.auth/login/aad" id="loginBtn" >Login</a></li>
<li><a href="/.auth/logout" id="logoutBtn">Logout</a></li>
We can run up the app locally using the swa cli.
$ swa start
Here it is.
Locally if we click login we are directed to a special screen to emulate the login process. We can enter some information such as a user name.
Once we are logged in we can use some JavaScript to query the “me” endpoint and retrieve information about the user.
<script>
async function getUserInfo() {
const response = await fetch('/.auth/me');
const payload = await response.json();
const { clientPrincipal } = payload;
return clientPrincipal;
}
(async () => {
const user = await getUserInfo()
const usernameSpan = document.getElementById('username');
usernameSpan.innerText = user ? user.userDetails : "";
})();
</script>
We can see below a username is shown in the welcome message the login button is also hidden and logout button revealed.
To deploy to azure
$ swa deploy
The command will prompt for some information and allow the creation of a new website and it will release to a preview environment by default. The public url to access the preview will be shown in the command line when the command completes.
This time clicking Login takes us to a microsoft hosted login page.
After logging in and accepting the consent page we are returned to our home page and the logged in state is shown.
I created the site on a free tier but I always tidy up my resources to make sure I don’t get charged for anything unexpectedly.
Static Web Apps give the ability to attach to an api which is called on the /api route. It would be great to experiment to see how auth works with this.