Authentication
Sep 17, 2021
See the code for this post on GitHub
Another reason I'm glad I went with Azure Static Web Apps: authentication couldn't be easier. Out of the box, I was able to set up a login page with GitHub and Twitter auth providers. I'd like to work with custom providers down the road, but this is a good start. SWA has built-in URLs to handle authenticating with those providers, as well as an endpoint to retrieve the logged-in user's claims and roles.
The most challenging piece of the puzzle had less to do with authentication and more to do with handling the post-login and post-logout redirect URLs. You can specify a URL to redirect to as a query parameter in your request to the auth provider, but it has to be fully qualified. I could have hard-coded the production URL in the code, but I'd rather have that URL pulled from an environment variable. Getting environment variables to play nice with both SvelteKit and Static Web Apps proved a bit challenging.
After some sleuthing and some trial-and-error, I was able to get SvelteKit to pick up environment variables from a local .env
file, though they have to be prefixed with VITE_
. Under the hood, SvelteKit uses Vite to generate its output, and Vite has a built-in constant for accessing environment variables during compilation: import.meta.env.VITE_FOO
, where VITE_FOO
is defined in the .env
file.
To get SWA to pick up the environment variable during its build, I can't use the configuration variables in Azure Portal the way I would for the Function endpoints. I had to add an env
section to the GitHub workflow .yml file and add the production URL there. It would be nice to be able to set this URL to the staging URL during pull requests, but I'll have to do some more research on that.
Client-side, I've added an authentication store that can be used to get/set the user's auth status. This works to automatically set the "Login" and "Logout" link in the site navigation. Svelte's built-in state management couldn't be simpler!
Coming up next: it's time to roll up my sleeves and start saving some of this Observation data in CosmosDB.
StarLog Links
All Posts
- MVP Wrap-Up [11/12/2021]
- Creating and Deleting [10/31/2021]
- The Vertical Slice [10/5/2021]
- Celestial Searches Revisited [9/23/2021]
- Authentication [9/17/2021]
- The SvelteKit Refactor [9/12/2021]
- Celestial Searches [8/29/2021]
- The Carbon Refactor [8/20/2021]
- Proof of Concept [6/16/2021]
- Laying the Foundation [5/24/2021]
- The Project Roadmap [5/19/2021]
- Introduction [5/18/2021]