As a follow-up on the presentation I did at CloudBrew about Azure Static Web Apps I want to write a series of blog posts.
- Part I - Using the VS Code Extension
- Part II - Using the Astro Static Site Generator
- Part III – Deploying to multiple environments
- Part IV – Password protect your environments
- Part V – Traffic splitting
- Part VI – Authentication using pre-configured providers
- Part VII – Application configuration using staticwebapp.config.json
- Part VIII – API Configuration
- Part IX – Injecting snippets
- Part X – Custom authentication
- Part XI – Authorization
- Part XII(this post) - Assign roles through an Azure function
We ended last post about Azure Static Web Apps talking about authorization and you can use role based security by assigning either a built-in role or a custom role. I showed how you could use invitations to assign a custom role.
Today I want to show a second option to assign a custom role using an Azure Function.
We start by creating an Azure Function that will be responsible for assigning roles. Every time a user successfully authenticates with an identity provider, the POST method calls the specified function. The function passes a JSON object in the request body that contains the user's information from the provider.
public static class RolesGet | |
{ | |
[FunctionName("roles-get")] | |
public static async Task<IActionResult> Run( | |
[HttpTrigger(AuthorizationLevel.Anonymous, "get","post", Route = "roles")] HttpRequest req, | |
ILogger log) | |
{ | |
var user = await System.Text.Json.JsonSerializer.DeserializeAsync<User>(req.Body); | |
var roles = new List<string>(){ "Admin", "User" }; | |
//Add your own implementation to get roles based on the user access token | |
return new OkObjectResult(new { roles }); | |
} | |
} | |
public record User(string UserId, string? AccessToken); |
Once we have our function, we need to configure the static web app to use this function. This can be done by setting the rolesSource
value of the auth
section in our staticwebapp.config.json
file:
{ | |
"platform": { "apiRuntime": "dotnet:6.0" }, | |
"auth":{ | |
"rolesSource": "/api/roles", | |
"identityProviders":{ | |
} | |
} | |
} |
If we now authenticate inside our application and call the .auth/me endpoint afterwards, we should see the custom roles coming from the api:
{ | |
"identityProvider": "github", | |
"userId": "d75b260a64504067bfc5b2905e3b8182", | |
"userDetails": "username", | |
"userRoles": ["anonymous", "authenticated", "Admin", "User"], | |
"claims": [{ | |
"typ": "name", | |
"val": "Azure Static Web Apps" | |
}] | |
} |
More information
Custom authentication in Azure Static Web Apps | Microsoft Learn