Search code examples
pythonazureactive-directoryazure-container-apps

How can I set authentication options for an azure container app via Python SDK?


We're using the Python ContainerAppsAPIClient library to deploy a container app to our azure estate, and it works great however I can't find any documentation on how to set the authentication on the container app either during or after it's been created. In the portal it's super easy to do, and there are some models I've found that appear to support it, but I'm not sure what other model I need to inject them into (if any?).

We're creating the ContainerApp in this kind of fashion:

container_app = ContainerApp(
    location=container_location,
    tags=tags,
    environment_id=f"/subscriptions/{subscription_id}/resourceGroups/{shared_infra_resource_group_name}/providers/Microsoft.App/managedEnvironments/{container_app_environment}",
    configuration=Configuration(
        active_revisions_mode="Single",
        secrets=secrets_config,
        registries=[registry_credentials],
        ingress=ingress,
    ),
    template=template,
    identity=identity,
)

Posible models I've found to use were: AzureActiveDirectoryLogin, AuthConfig etc. but no idea where to put them.. the documentation is pretty much non-existent around this.

More specifically we want to put the container app being our azure active directory login (on the same subscription), using the SDK. Below shows what I did manually in the portal that I'd like to recreate using the SDK:

A screenshot of the azure portal

I've tried the following code:

client.container_apps_auth_configs.create_or_update(
        resource_group_name=resource_group_name,
        container_app_name=container_app_name,
        auth_config_name="current", # Code: AuthConfigInvalidName. Message: The name 'label-studio' is disallowed for authconfigs, please use the name 'current'.
        auth_config_envelope=AuthConfig(
            platform=AuthPlatform(
                enabled=True
            ),
            global_validation=GlobalValidation(
                unauthenticated_client_action="Return401"
            ), # Some more settings for Auth if you want 'em
            identity_providers=IdentityProviders(
                azure_active_directory=AzureActiveDirectory(
                    enabled=True,
                    registration=AzureActiveDirectoryRegistration(
                        open_id_issuer="https://sts.windows.net/REDACTED-UUID/v2.0" # The azure AD app registration uri
                    ),
                    login=AzureActiveDirectoryLogin(),

                )
            ),
            login=Login(),
            http_settings=HttpSettings()
        )
    )

Except that this results in the portal showing this on the auth page:

All traffic is blocked, and requests will receive an HTTP 401 Unauthorized. This is because there is an authentication requirement, but no identity provider is configured. Click 'Remove authentication' to disable this feature and remove the access restriction. Or click 'Add identity provider' to configure a way for clients to authenticate themselves.

No idea why as it looks like I did provide an identity provider


Solution

  • When I ran your code in my environment, I too got same error in Portal as below:

    enter image description here

    In my case, adding Microsoft as identity provider worked when I included existing application clientId and secret in Python code.

    For that, you can register one Azure AD application with Redirect URI as <container-app-url>/.auth/login/aad/callback like this:

    enter image description here

    Now, create one client secret in above app and add that secret value in Container app Secret tab:

    enter image description here

    When I ran below modified code by including client ID and secret of existing app, I got response like this:

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.appcontainers import ContainerAppsAPIClient
    
    def main():
        client = ContainerAppsAPIClient(
            credential=DefaultAzureCredential(),
            subscription_id="sub_id",
        )
    
        response = client.container_apps_auth_configs.create_or_update(
            resource_group_name="Sri",
            container_app_name="containerapp04",
            auth_config_name="current",
            auth_config_envelope={
                "properties": {
                    "globalValidation": {"unauthenticatedClientAction": "Return401"},
                    "identityProviders": {
                        "azureActiveDirectory": {"enabled": True, "isAutoProvisioned": True,"login": {},"registration": {"clientId": "appId","clientSecretSettingName": "secret","openIdIssuer": "https://sts.windows.net/tenantId/v2.0"}, "validation":{"allowedAudiences":["appId"]}}
                    },
                    "platform": {"enabled": True},
                }
            },
        )
        print(response)
    
    if __name__ == "__main__":
        main()
    

    Response:

    enter image description here

    To confirm that, I checked the same in Portal where Microsoft is configured as identity provider successfully in container app:

    enter image description here

    When I clicked on Edit option, I got below screen with identity provider properties:

    enter image description here

    Reference: Create or Update Auth Config in Azure Container App using Python SDK · GitHub