DEV Community

Aaron Powell for Microsoft Azure

Posted on • Originally published at aaron-powell.com on

6 2

Making Auth Simpler for Static Web App APIs

Azure Static Web Apps has built-in Authentication and Authorization for both the web and API part of the application.

At the end of last year, I wrote about a package to make it easier in React apps to work with auth and get access to the user details. But this still left a gap in the APIs, your APIs need to parse the JSON out of a custom header, which is base64 encoded. All a bit complicated in my book.

So, I decided to make another package to help with that, @aaronpowell/static-web-apps-api-auth.

Using the package

The package exposes two functions, isAuthenticated and getUserInfo. Here's an example of an API that uses the package:

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import {
  getUserInfo,
  isAuthenticated,
} from "@aaronpowell/static-web-apps-api-auth";

const httpTrigger: AzureFunction = async function (
  context: Context,
  req: HttpRequest
): Promise<void> {
  context.log("HTTP trigger function processed a request.");

  if (!isAuthenticated(req)) {
    context.res = {
      body: "You are not logged in at the moment",
    };
  } else {
    const { clientPrincipal } = getUserInfo(req);

    context.res = {
      body: `Thanks for logging in ${
        clientPrincipal.userDetails
      }. You logged in via ${
        clientPrincipal.identityProvider
      } and have the roles ${clientPrincipal.userRoles.join(", ")}`,
    };
  }
};

export default httpTrigger;
Enter fullscreen mode Exit fullscreen mode

The isAuthenticated function takes the request that the API receives and returns a boolean of whether the user is authenticated or not, and the getUserInfo unpacks the header data into a JavaScript object (with TypeScript typings) that you can work with.

Hopefully this makes it just that bit easier to work with authenticated experiences on Static Web Apps.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series