references/auth-best-practices.md
# Azure Authentication Best Practices
> Source: [Microsoft — Passwordless connections for Azure services](https://learn.microsoft.com/azure/developer/intro/passwordless-overview) and [Azure Identity client libraries](https://learn.microsoft.com/dotnet/azure/sdk/authentication/).
## Golden Rule
Use **managed identities** and **Azure RBAC** in production. Reserve `DefaultAzureCredential` for **local development only**.
## Authentication by Environment
| Environment | Recommended Credential | Why |
|---|---|---|
| **Production (Azure-hosted)** | `ManagedIdentityCredential` (system- or user-assigned) | No secrets to manage; auto-rotated by Azure |
| **Production (on-premises)** | `ClientCertificateCredential` or `WorkloadIdentityCredential` | Deterministic; no fallback chain overhead |
| **CI/CD pipelines** | `AzurePipelinesCredential` / `WorkloadIdentityCredential` | Scoped to pipeline identity |
| **Local development** | `DefaultAzureCredential` | Chains CLI, PowerShell, and VS Code credentials for convenience |
## Why Not `DefaultAzureCredential` in Production?
1. **Unpredictable fallback chain** — walks through multiple credential types, adding latency and making failures harder to diagnose.
2. **Broad surface area** — checks environment variables, CLI tokens, and other sources that should not exist in production.
3. **Non-deterministic** — which credential actually authenticates depends on the environment, making behavior inconsistent across deployments.
4. **Performance** — each failed credential attempt adds network round-trips before falling back to the next.
## Production Patterns
### .NET
```csharp
using Azure.Identity;
var credential = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") == "Development"
? new DefaultAzureCredential() // local dev — uses CLI/VS credentials
: new ManagedIdentityCredential(); // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredential("<client-id>")
```
### TypeScript / JavaScript
```typescript
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
const credential = process.env.NODE_ENV === "development"
? new DefaultAzureCredential() // local dev — uses CLI/VS credentials
: new ManagedIdentityCredential(); // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredential("<client-id>")
```
### Python
```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
credential = (
DefaultAzureCredential() # local dev — uses CLI/VS credentials
if os.getenv("AZURE_FUNCTIONS_ENVIRONMENT") == "Development"
else ManagedIdentityCredential() # production — deterministic, no fallback chain
)
# For user-assigned identity: ManagedIdentityCredential(client_id="<client-id>")
```
### Java
```java
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
var credential = "Development".equals(System.getenv("AZURE_FUNCTIONS_ENVIRONMENT"))
? new DefaultAzureCredentialBuilder().build() // local dev — uses CLI/VS credentials
: new ManagedIdentityCredentialBuilder().build(); // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredentialBuilder().clientId("<client-id>").build()
```
## Local Development Setup
`DefaultAzureCredential` is ideal for local dev because it automatically picks up credentials from developer tools:
1. **Azure CLI** — `az login`
2. **Azure Developer CLI** — `azd auth login`
3. **Azure PowerShell** — `Connect-AzAccount`
4. **Visual Studio / VS Code** — sign in via Azure extension
```typescript
import { DefaultAzureCredential } from "@azure/identity";
// Local development only — uses CLI/PowerShell/VS Code credentials
const credential = new DefaultAzureCredential();
```
## Environment-Aware Pattern
Detect the runtime environment and select the appropriate credential. The key principle: use `DefaultAzureCredential` only when running locally, and a specific credential in production.
> **Tip:** Azure Functions sets `AZURE_FUNCTIONS_ENVIRONMENT` to `"Development"` when running locally. For App Service or containers, use any environment variable you control (e.g. `NODE_ENV`, `ASPNETCORE_ENVIRONMENT`).
```typescript
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
function getCredential() {
if (process.env.NODE_ENV === "development") {
return new DefaultAzureCredential(); // picks up az login / VS Code creds
}
return process.env.AZURE_CLIENT_ID
? new ManagedIdentityCredential(process.env.AZURE_CLIENT_ID) // user-assigned
: new ManagedIdentityCredential(); // system-assigned
}
```
## Security Checklist
- [ ] Use managed identity for all Azure-hosted apps
- [ ] Never hardcode credentials, connection strings, or keys
- [ ] Apply least-privilege RBAC roles at the narrowest scope
- [ ] Use `ManagedIdentityCredential` (not `DefaultAzureCredential`) in production
- [ ] Store any required secrets in Azure Key Vault
- [ ] Rotate secrets and certificates on a schedule
- [ ] Enable Microsoft Defender for Cloud on production resources
## Further Reading
- [Passwordless connections overview](https://learn.microsoft.com/azure/developer/intro/passwordless-overview)
- [Managed identities overview](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview)
- [Azure RBAC overview](https://learn.microsoft.com/azure/role-based-access-control/overview)
- [.NET authentication guide](https://learn.microsoft.com/dotnet/azure/sdk/authentication/)
- [Python identity library](https://learn.microsoft.com/python/api/overview/azure/identity-readme)
- [JavaScript identity library](https://learn.microsoft.com/javascript/api/overview/azure/identity-readme)
- [Java identity library](https://learn.microsoft.com/java/api/overview/azure/identity-readme)
references/sdk/azure-mgmt-applicationinsights-dotnet.md
# Application Insights Management — .NET SDK Quick Reference
> Condensed from **azure-mgmt-applicationinsights-dotnet**. Full patterns
> (web tests, workbooks, API keys, linked storage)
> in the **azure-mgmt-applicationinsights-dotnet** plugin skill if installed.
## Install
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
## Quick Start
> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.
```csharp
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
using Azure.Identity;
ArmClient client = new ArmClient(new DefaultAzureCredential());
var components = resourceGroup.GetApplicationInsightsComponents();
```
## Best Practices
- Use workspace-based App Insights (current standard)
- Link to Log Analytics for better querying
- Set appropriate retention to balance cost vs data availability
- Use sampling to reduce costs for high-volume applications
- Store connection string securely in Key Vault or managed identity
- Enable multiple test locations for accurate availability monitoring
- Use workbooks for custom dashboards and analysis
- Set up alerts based on availability tests and metrics
- Tag resources for cost allocation and organization
- Use private endpoints for secure data ingestion
references/sdk/azure-monitor-ingestion-java.md
# Azure Monitor Ingestion — Java SDK Quick Reference
> Condensed from **azure-monitor-ingestion-java**. Full patterns (async
> Reactor upload, concurrency, error consumers, log entry models)
> in the **azure-monitor-ingestion-java** plugin skill if installed.
## Install
```xml
<dependency><groupId>com.azure</groupId><artifactId>azure-monitor-ingestion</artifactId></dependency>
<dependency><groupId>com.azure</groupId><artifactId>azure-identity</artifactId></dependency>
```
## Quick Start
```java
import com.azure.monitor.ingestion.LogsIngestionClient;
import com.azure.monitor.ingestion.LogsIngestionClientBuilder;
import com.azure.identity.DefaultAzureCredentialBuilder;
LogsIngestionClient client = new LogsIngestionClientBuilder()
.endpoint("<data-collection-endpoint>")
.credential(new DefaultAzureCredentialBuilder().build()).buildClient();
client.upload("<dcr-rule-id>", "<stream-name>", logs);
```
## Best Practices
- Batch logs rather than uploading one at a time
- Set maxConcurrency via LogsUploadOptions for large uploads
- Handle partial failures with setLogsUploadErrorConsumer
- Log entry fields must match DCR transformation expectations
- Include TimeGenerated timestamp field in entries
- Reuse client instance throughout application
- Use LogsIngestionAsyncClient for reactive/high-throughput patterns
references/sdk/azure-monitor-ingestion-py.md
# Azure Monitor Ingestion — Python SDK Quick Reference
> Condensed from **azure-monitor-ingestion-py**. Full patterns (async upload,
> sovereign clouds, error callbacks, JSON file upload)
> in the **azure-monitor-ingestion-py** plugin skill if installed.
## Install
pip install azure-monitor-ingestion azure-identity
## Quick Start
> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.
```python
from azure.monitor.ingestion import LogsIngestionClient
from azure.identity import DefaultAzureCredential
client = LogsIngestionClient(endpoint=DCE_ENDPOINT, credential=DefaultAzureCredential())
client.upload(rule_id=DCR_RULE_ID, stream_name=STREAM_NAME, logs=logs)
```
## Best Practices
- Use DefaultAzureCredential for **local development only**. In production, use ManagedIdentityCredential — see [auth-best-practices.md](../auth-best-practices.md)
- Handle errors gracefully with on_error callback for partial failures
- Include TimeGenerated field — required for all logs
- Match DCR schema — log fields must match DCR column definitions
- Use async client for high-throughput scenarios
- SDK handles batching automatically (1MB chunks, gzip, parallel)
- Monitor ingestion status in Log Analytics
- Use context manager for proper client cleanup
## Non-Obvious Patterns
- DCE endpoint: `https://<name>.<region>.ingest.monitor.azure.com`
- Stream names: `Custom-<TableName>_CL` (custom) or `Microsoft-<TableName>` (built-in)
references/sdk/azure-monitor-opentelemetry-exporter-py.md
# Azure Monitor OpenTelemetry Exporter — Python SDK Quick Reference
> Condensed from **azure-monitor-opentelemetry-exporter-py**. Full patterns
> (metric exporter, log exporter, offline storage, sovereign clouds)
> in the **azure-monitor-opentelemetry-exporter-py** plugin skill if installed.
## Install
pip install azure-monitor-opentelemetry-exporter
## Quick Start
```python
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter() # reads APPLICATIONINSIGHTS_CONNECTION_STRING
```
## Best Practices
- Use BatchSpanProcessor for production (not SimpleSpanProcessor)
- Use ApplicationInsightsSampler for consistent sampling across services
- Enable offline storage for reliability in production
- Use AAD authentication instead of instrumentation keys
- Set export intervals appropriate for your workload
- Use the distro (azure-monitor-opentelemetry) unless you need custom pipelines
references/sdk/azure-monitor-opentelemetry-py.md
# Azure Monitor OpenTelemetry — Python SDK Quick Reference
> Condensed from **azure-monitor-opentelemetry-py**. Full patterns
> (Flask/Django/FastAPI, custom metrics, sampling, live metrics)
> in the **azure-monitor-opentelemetry-py** plugin skill if installed.
## Install
pip install azure-monitor-opentelemetry
## Quick Start
```python
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
```
## Best Practices
- Call configure_azure_monitor() early — before importing instrumented libraries
- Use environment variables for connection string in production
- Set cloud role name for multi-service Application Map
- Enable sampling in high-traffic applications
- Use structured logging for better log analytics queries
- Add custom attributes to spans for better debugging
- Use AAD authentication for production workloads
references/sdk/azure-monitor-opentelemetry-ts.md
# Azure Monitor OpenTelemetry — TypeScript SDK Quick Reference
> Condensed from **azure-monitor-opentelemetry-ts**. Full patterns
> (ESM loader, custom span processors, manual exporters, live metrics)
> in the **azure-monitor-opentelemetry-ts** plugin skill if installed.
## Install
npm install @azure/monitor-opentelemetry
## Quick Start
```typescript
import { useAzureMonitor } from "@azure/monitor-opentelemetry";
useAzureMonitor({
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
}
});
```
## Best Practices
- Call useAzureMonitor() first — before importing other modules
- Use ESM loader for ESM projects — `--import @azure/monitor-opentelemetry/loader`
- Enable offline storage for reliable telemetry in disconnected scenarios
- Set sampling ratio for high-traffic applications
- Add custom dimensions — use span processors for enrichment
- Graceful shutdown — call shutdownAzureMonitor() to flush telemetry
references/sdk/azure-monitor-query-java.md
# Azure Monitor Query — Java SDK Quick Reference
> Condensed from **azure-monitor-query-java**. Full patterns (batch queries,
> model mapping, multi-workspace queries, sovereign clouds)
> in the **azure-monitor-query-java** plugin skill if installed.
## Install
```xml
<dependency><groupId>com.azure</groupId><artifactId>azure-monitor-query</artifactId></dependency>
<dependency><groupId>com.azure</groupId><artifactId>azure-identity</artifactId></dependency>
```
## Quick Start
> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.
```java
import com.azure.monitor.query.LogsQueryClient;
import com.azure.monitor.query.LogsQueryClientBuilder;
import com.azure.identity.DefaultAzureCredentialBuilder;
LogsQueryClient client = new LogsQueryClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build()).buildClient();
```
## Best Practices
- Use batch queries to combine multiple queries into a single request
- Set appropriate timeouts for long-running queries
- Limit result size with `top` or `take` in Kusto queries
- Use projections (`project`) to select only needed columns
- Check query status and handle PARTIAL_FAILURE gracefully
- Cache metrics results when appropriate
- Migrate to `azure-monitor-query-logs` and `azure-monitor-query-metrics` (this package is deprecated)
references/sdk/azure-monitor-query-py.md
# Azure Monitor Query — Python SDK Quick Reference
> Condensed from **azure-monitor-query-py**. Full patterns (batch queries,
> DataFrame conversion, async clients, dimension filters)
> in the **azure-monitor-query-py** plugin skill if installed.
## Install
pip install azure-monitor-query azure-identity
## Quick Start
> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.
```python
from azure.monitor.query import LogsQueryClient, MetricsQueryClient
from azure.identity import DefaultAzureCredential
client = LogsQueryClient(DefaultAzureCredential())
```
## Best Practices
- Use timedelta for relative time ranges
- Handle partial results for large queries (check LogsQueryStatus.PARTIAL)
- Use batch queries when running multiple queries
- Set appropriate granularity for metrics to reduce data points
- Convert to DataFrame for easier data analysis
- Use aggregations to summarize metric data
- Filter by dimensions to narrow metric results