Azure Static Web App – Only Allow Authenticated Users (Entra, B2C): A Step-by-Step Guide
Image by Gwynneth - hkhazo.biz.id

Azure Static Web App – Only Allow Authenticated Users (Entra, B2C): A Step-by-Step Guide

Posted on

Azure Static Web Apps (SWAs) have revolutionized the way we build and deploy modern web applications. One of the most crucial aspects of any web app is security, and Azure SWAs provide robust authentication mechanisms to ensure that only authorized users can access your app. In this article, we’ll explore how to configure an Azure Static Web App to only allow authenticated users using Azure Active Directory (Azure AD) and Azure Active Directory B2C (Azure AD B2C).

What is Azure Active Directory (Azure AD)?

Azure Active Directory (Azure AD) is a cloud-based identity and access management solution that provides secure access to resources and applications. It allows users to sign in and access multiple applications and resources with a single set of credentials. Azure AD provides a robust and scalable identity platform that integrates with a wide range of applications and services.

What is Azure Active Directory B2C (Azure AD B2C)?

Azure Active Directory B2C (Azure AD B2C) is a cloud-based identity and access management solution that enables you to customize and control how users interact with your applications. It provides a secure and scalable identity platform that allows you to manage consumer identities and authenticate users. Azure AD B2C is designed for consumer-facing applications and provides features such as customizable user flows, password reset, and multi-factor authentication.

Configuring Azure Static Web App Authentication

To configure authentication for your Azure Static Web App, you’ll need to follow these steps:

  1. Create an Azure AD or Azure AD B2C tenant

  2. Register your Azure Static Web App with Azure AD or Azure AD B2C

  3. Configure authentication settings in Azure Static Web App

  4. Implement authentication logic in your application code

Step 1: Create an Azure AD or Azure AD B2C Tenant

To create an Azure AD or Azure AD B2C tenant, follow these steps:

  • Sign in to the Azure portal (https://portal.azure.com)

  • Click on “Create a resource” and search for “Azure Active Directory” or “Azure Active Directory B2C”

  • Click on “Create” and follow the wizard to create a new Azure AD or Azure AD B2C tenant

Step 2: Register Your Azure Static Web App with Azure AD or Azure AD B2C

To register your Azure Static Web App with Azure AD or Azure AD B2C, follow these steps:

  • Sign in to the Azure portal (https://portal.azure.com)

  • Navigate to your Azure AD or Azure AD B2C tenant

  • Click on “App registrations” and then click on “New registration”

  • Enter a name for your application and select “Web” as the platform

  • Enter the redirect URI for your Azure Static Web App (e.g., https://.azurestaticapps.net)

  • Click on “Register” to create the app registration

Step 3: Configure Authentication Settings in Azure Static Web App

To configure authentication settings in Azure Static Web App, follow these steps:

  • Sign in to the Azure portal (https://portal.azure.com)

  • Navigate to your Azure Static Web App

  • Click on “Authentication” under “Security” in the left menu

  • Click on “Add a provider” and select “Azure Active Directory” or “Azure Active Directory B2C”

  • Select the app registration you created in Step 2

  • Configure any additional settings as required (e.g., scopes, permissions)

  • Click on “Save” to save the authentication settings

Step 4: Implement Authentication Logic in Your Application Code

To implement authentication logic in your application code, you’ll need to use a library such as the Microsoft Authentication Library (MSAL) for JavaScript. Here’s an example of how you can use MSAL to authenticate users:


import { PublicClientApplication } from '@azure/msal-browser';

const clientApp = new PublicClientApplication(
  'your_client_id',
  'https://login.microsoftonline.com/' + 'your_tenant_id'
);

async function handleLogin() {
  try {
    const response = await clientApp.loginPopup({
      scopes: ['openid', 'profile', 'https://graph.microsoft.com/.default'],
      redirectUri: 'https://.azurestaticapps.net'
    });

    if (response !== null) {
      const accessToken = response.accessToken;
      // Use the access token to authenticate the user
    } else {
      console.error('Error logging in:', error);
    }
  } catch (error) {
    console.error('Error logging in:', error);
  }
}

Only Allow Authenticated Users

Once you’ve configured authentication for your Azure Static Web App, you can restrict access to only authenticated users by using the Azure Static Web App authentication middleware. Here’s an example of how you can use the middleware to only allow authenticated users:


import { NextApiRequest, NextApiResponse } from 'next';
import { auth } from '@azure/static-app-auth';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (!auth.validate(req)) {
    return res.status(401).send('Unauthorized');
  }

  // Only authenticated users can access this route
  return res.send('Hello, authenticated user!');
};

export default handler;
Middleware Description
auth.validate(req) Validates the authentication token in the request
auth.getUser(req) Returns the authenticated user’s details

Conclusion

In this article, we’ve explored how to configure an Azure Static Web App to only allow authenticated users using Azure Active Directory (Azure AD) and Azure Active Directory B2C (Azure AD B2C). By following these steps, you can ensure that only authorized users can access your Azure Static Web App.

Remember to replace the placeholders (e.g., your_client_id, your_tenant_id) with the actual values for your Azure AD or Azure AD B2C tenant.

If you have any questions or need further assistance, feel free to ask in the comments below!

Happy coding!

Frequently Asked Question

Get the scoop on Azure Static Web Apps and how to secure them with authenticated users only!

What is Azure Static Web Apps and how does it relate to authenticated users?

Azure Static Web Apps (SWA) is a service that allows you to build, deploy, and host modern web applications with ease. With SWA, you can create fast, scalable, and secure websites that can be accessed by anyone on the internet. However, if you want to restrict access to only authenticated users, you’ll need to configure your SWA to integrate with an identity provider like Azure Active Directory (Azure AD) or Azure AD B2C. This allows you to control who can access your app and ensure that only authorized users can view its content.

How do I set up Azure AD B2C with my Azure Static Web App?

To set up Azure AD B2C with your Azure Static Web App, you’ll need to follow these steps: 1) Create an Azure AD B2C tenant and register your application, 2) Configure the Azure AD B2C authentication flow, 3) Install the Azure AD B2C SDK in your SWA project, and 4) Update your SWA configuration to use Azure AD B2C authentication. You can find more detailed instructions in the Azure documentation.

What is the difference between Azure AD and Azure AD B2C?

Azure AD and Azure AD B2C are both identity and access management solutions, but they serve different purposes. Azure AD is designed for enterprise scenarios, where you need to manage access to resources for employees or partners within your organization. Azure AD B2C, on the other hand, is meant for customer-facing applications, where you need to authenticate and authorize users who are not part of your organization. Azure AD B2C provides more flexibility and customization options for user journeys and authentication flows.

How do I restrict access to my Azure Static Web App to only authenticated users?

To restrict access to your Azure Static Web App to only authenticated users, you’ll need to configure your SWA to use Azure AD B2C authentication. Once authenticated, users will receive an access token that’s validated by Azure AD B2C. You can then use this token to authorize access to your SWA. You can do this by adding authentication middleware to your SWA project, which will redirect unauthenticated users to the Azure AD B2C login page.

Can I use other identity providers with Azure Static Web Apps?

Yes, you can use other identity providers with Azure Static Web Apps. While Azure AD and Azure AD B2C are popular choices, you can also integrate your SWA with other identity providers like Google, Facebook, or GitHub. This allows you to provide users with more options for authentication and authorization. You can use OpenID Connect or OAuth 2.0 protocols to integrate your SWA with these external identity providers.

Leave a Reply

Your email address will not be published. Required fields are marked *