Skip to content

Instantly share code, notes, and snippets.

@emandret
Created March 22, 2023 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emandret/e7ec265a6d9e338e13ed1928f604b0c0 to your computer and use it in GitHub Desktop.
Save emandret/e7ec265a6d9e338e13ed1928f604b0c0 to your computer and use it in GitHub Desktop.
Terraform snippet to setup Azure AD auth for an Azure web app using a custom OIDC provider
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "=3.45.0"
}
}
}
provider "azurerm" {
features {}
}
data "azurerm_client_config" "current" {}
locals {
app_name = "oidc-from-scratch"
oidc_provider_name = "oidc_from_scratch"
oidc_discovery_document = "https://login.microsoftonline.com/${data.azurerm_client_config.current.tenant_id}/v2.0/.well-known/openid-configuration"
}
resource "azurerm_resource_group" "main_rg" {
name = "oidc-test"
location = "eastus"
}
resource "azurerm_service_plan" "main_asp" {
name = "oidc-test"
location = azurerm_resource_group.main_rg.location
resource_group_name = azurerm_resource_group.main_rg.name
os_type = "Linux"
sku_name = "S2"
}
resource "azuread_application" "oidc_resource_stub" {
display_name = "${local.app_name}-stub"
owners = [data.azurerm_client_config.current.object_id]
web {
homepage_url = "https://${local.app_name}.azurewebsites.net"
implicit_grant {
access_token_issuance_enabled = false
id_token_issuance_enabled = false
}
redirect_uris = [
"https://${local.app_name}.azurewebsites.net/.auth/login/${local.oidc_provider_name}/callback"
]
}
}
resource "azuread_application_password" "client_secret" {
application_object_id = azuread_application.oidc_resource_stub.object_id
}
resource "azurerm_linux_web_app" "oidc_app" {
name = local.app_name
location = azurerm_resource_group.main_rg.location
resource_group_name = azurerm_resource_group.main_rg.name
service_plan_id = azurerm_service_plan.main_asp.id
app_settings = {
"${upper(local.oidc_provider_name)}_PROVIDER_AUTHENTICATION_SECRET" = azuread_application_password.client_secret.value
}
auth_settings_v2 {
login {
preserve_url_fragments_for_logins = false
token_store_enabled = false
}
auth_enabled = true
require_authentication = true
unauthenticated_action = "RedirectToLoginPage"
default_provider = local.oidc_provider_name
custom_oidc_v2 {
name = local.oidc_provider_name
# NOTE: the token has an audience set for an App Registration which represents the Web App
client_id = azuread_application.oidc_resource_stub.application_id
openid_configuration_endpoint = local.oidc_discovery_document
}
}
site_config {
application_stack {
node_version = "18-lts"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment