best practices
66 TopicsSuperfast using Web App and Managed Identity to invoke Function App triggers
TOC Introduction Setup References 1. Introduction Many enterprises prefer not to use App Keys to invoke Function App triggers, as they are concerned that these fixed strings might be exposed. This method allows you to invoke Function App triggers using Managed Identity for enhanced security. I will provide examples in both Bash and Node.js. 2. Setup 1. Create a Linux Python 3.11 Function App 1.1. Configure Authentication to block unauthenticated callers while allowing the Web App’s Managed Identity to authenticate. Identity Provider Microsoft Choose a tenant for your application and it's users Workforce Configuration App registration type Create Name [automatically generated] Client Secret expiration [fit-in your business purpose] Supported Account Type Any Microsoft Entra Directory - Multi-Tenant Client application requirement Allow requests from any application Identity requirement Allow requests from any identity Tenant requirement Use default restrictions based on issuer Token store [checked] 1.2. Create an anonymous trigger. Since your app is already protected by App Registration, additional Function App-level protection is unnecessary; otherwise, you will need a Function Key to trigger it. 1.3. Once the Function App is configured, try accessing the endpoint directly—you should receive a 401 Unauthorized error, confirming that triggers cannot be accessed without proper Managed Identity authorization. 1.4. After making these changes, wait 10 minutes for the settings to take effect. 2. Create a Linux Node.js 20 Web App and Obtain an Access Token and Invoke the Function App Trigger Using Web App (Bash Example) 2.1. Enable System Assigned Managed Identity in the Web App settings. 2.2. Open Kudu SSH Console for the Web App. 2.3. Run the following commands, making the necessary modifications: subscriptionsID → Replace with your Subscription ID. resourceGroupsID → Replace with your Resource Group ID. application_id_uri → Replace with the Application ID URI from your Function App’s App Registration. https://az-9640-faapp.azurewebsites.net/api/test_trigger → Replace with the corresponding Function App trigger URL. # Please setup the target resource to yours subscriptionsID="01d39075-XXXX-XXXX-XXXX-XXXXXXXXXXXX" resourceGroupsID="XXXX" # Variable Setting (No need to change) identityEndpoint="$IDENTITY_ENDPOINT" identityHeader="$IDENTITY_HEADER" application_id_uri="api://9c0012ad-XXXX-XXXX-XXXX-XXXXXXXXXXXX" # Install necessary tool apt install -y jq # Get Access Token tokenUri="${identityEndpoint}?resource=${application_id_uri}&api-version=2019-08-01" accessToken=$(curl -s -H "Metadata: true" -H "X-IDENTITY-HEADER: $identityHeader" "$tokenUri" | jq -r '.access_token') echo "Access Token: $accessToken" # Run Trigger response=$(curl -s -o response.json -w "%{http_code}" -X GET "https://az-9640-myfa.azurewebsites.net/api/my_test_trigger" -H "Authorization: Bearer $accessToken") echo "HTTP Status Code: $response" echo "Response Body:" cat response.json 2.4. If everything is set up correctly, you should see a successful invocation result. 3. Invoke the Function App Trigger Using Web App (nodejs Example) I have also provide my example, which you can modify accordingly and save it to /home/site/wwwroot/callFunctionApp.js and run it cd /home/site/wwwroot/ vi callFunctionApp.js npm init -y npm install azure/identity axios node callFunctionApp.js // callFunctionApp.js const { DefaultAzureCredential } = require("@azure/identity"); const axios = require("axios"); async function callFunctionApp() { try { const applicationIdUri = "api://9c0012ad-XXXX-XXXX-XXXX-XXXXXXXXXXXX"; // Change here const credential = new DefaultAzureCredential(); console.log("Requesting token..."); const tokenResponse = await credential.getToken(applicationIdUri); if (!tokenResponse || !tokenResponse.token) { throw new Error("Failed to acquire access token"); } const accessToken = tokenResponse.token; console.log("Token acquired:", accessToken); const apiUrl = "https://az-9640-myfa.azurewebsites.net/api/my_test_trigger"; // Change here console.log("Calling the API now..."); const response = await axios.get(apiUrl, { headers: { Authorization: `Bearer ${accessToken}`, }, }); console.log("HTTP Status Code:", response.status); console.log("Response Body:", response.data); } catch (error) { console.error("Failed to call the function", error.response ? error.response.data : error.message); } } callFunctionApp(); Below is my execution result: 3. References Tutorial: Managed Identity to Invoke Azure Functions | Microsoft Learn How to Invoke Azure Function App with Managed Identity | by Krizzia 🤖 | Medium Configure Microsoft Entra authentication - Azure App Service | Microsoft Learn192Views0likes0CommentsAzure App Service Auto-Heal: Capturing Relevant Data During Performance Issues
Introduction Azure App Service is a powerful platform that simplifies the deployment and management of web applications. However, maintaining application performance and availability is crucial. When performance issues arise, identifying the root cause can be challenging. This is where Auto-Heal in Azure App Service becomes a game-changer. Auto-Heal is a diagnostic and recovery feature that allows you to proactively detect and mitigate issues affecting your application’s performance. It enables automatic corrective actions and helps capture vital diagnostic data to troubleshoot problems efficiently. In this blog, we’ll explore how Auto-Heal works, its configuration, and how it assists in diagnosing performance bottlenecks. What is Auto-Heal in Azure App Service? Auto-Heal is a self-healing mechanism that allows you to define custom rules to detect and respond to problematic conditions in your application. When an issue meets the defined conditions, Auto-Heal can take actions such as: Recycling the application process Collecting diagnostic dumps Logging additional telemetry for analysis Triggering a custom action By leveraging Auto-Heal, you can minimize downtime, improve reliability, and reduce manual intervention for troubleshooting. Configuring Auto-Heal in Azure App Service To set up Auto-Heal, follow these steps: Access Auto-Heal Settings Navigate to the Azure Portal. Go to your App Service. Select Diagnose and Solve Problems. Search for Auto-Heal or go to Diagnostic tools tile and select Auto-Heal. Define Auto-Heal Rules Auto-Heal allows you to define rules based on: Request Duration: If a request takes too long, trigger an action. Memory Usage: If memory consumption exceeds a certain threshold. HTTP Status Codes: If multiple requests return specific status codes (e.g., 500 errors). Request Count: If excessive requests occur within a defined time frame. Configure Auto-Heal Actions Once conditions are set, you can configure one or more of the following actions: Recycle Process: Restart the worker process to restore the application. Log Events: Capture logs for further analysis. Custom Action: You can do the following: Run Diagnostics: Gather diagnostic data (Memory Dump, CLR Profiler, CLR Profiler with Threads Stacks, Java Memory Dump, Java Thread Dump) for troubleshooting. Run any Executable: Run scripts to automate corrective measures. Capturing Relevant Data During Performance Issues One of the most powerful aspects of Auto-Heal is its ability to capture valuable diagnostic data when an issue occurs. Here’s how: Collecting Memory Dumps Memory dumps provide insights into application crashes, high CP or high memory usage. These can be analyzed using WinDbg or DebugDiag. Enabling Logs for Deeper Insights Auto-Heal logs detailed events in Kudu Console, Application Insights, and Azure Monitor Logs. This helps identify patterns and root causes. Collecting CLR Profiler traces CLR Profiler traces capture call stacks and exceptions, providing a user-friendly report for diagnosing slow responses and HTTP issues at the application code level. In this article, we will cover the steps to configure an Auto-Heal rule for the following performance issues: To capture a .NET Profiler/CLR Profiler trace for Slow responses. To capture a .NET Profiler/CLR Profiler trace for HTTP 5XX Status codes. To capture Memory dump for a High Memory usage. Auto-Heal rule to capture .NET Profiler trace for Slow response: 1. Navigate to your App Service on Azure Portal, and click on Diagnose and Solve problems: 2. Search for Auto-Heal or go to Diagnostic tools tile and select Auto-Heal: 3. Click on 'On': 4. Select Request Duration and click on Add Slow Request rule: 5. Add the following information with respect to how much slowness you are facing: After how many slow requests you want this condition to kick in? - After how many slow requests you want this Auto-Heal rule to start writing/capturing relevant data. What should be minimum duration (in seconds) for these slow requests? - How many seconds should the request take to be considered as a slow request. What is the time interval (in seconds) in which the above condition should be met? - In how many seconds, the above defined slow request should occur. What is the request path (leave blank for all requests)? - If there is a specific URL which is slow, you can add that in this section or leave it as blank. In the below screenshot, the rule is set for this example "1 request taking 30 seconds in 5 minutes/300 seconds should trigger this rule" Add the values in the text boxes available and click "Ok" 6. Select Custom Action and select CLR Profiler with Thread Stacks option: 7. The tool options provide three choices: CollectKillAnalyze: If this option is selected, the tool will collect the data, analyze and generate the report and recycle the process. CollectLogs: If this option is selected, the tool will collect the data only. It will not analyze and generate the report and recycle the process. Troubleshoot: If this option is selected, the tool will collect the data and analyze and generate the report, but it will not recycle the process. Select the option, according to your scenario: Click on "Save". 8. Review the new settings of the rule: Clicking on "Save" will cause a restart as this is a configuration level change and for this to get in effect a restart is required. So, it is advised to make such changes in non-business hours. 9. Click on "Save". Once you click on Save, the app will get restarted and the rule will become active and monitor for Slow requests. Auto-Heal rule to capture .NET Profiler trace for HTTP 5XX Status code: For this scenario, Steps 1, 2, 3 will remain the same as above (from the Slow requests scenario). There will be following changes: 1. Select Status code and click on Add Status Code rule 2. Add the following value with respect to what Status code or range of status code you want this rule to be triggered by: Do you want to set this rule for a specific status code or a range of status codes? - Is it single status code you want to set this rule for or a range of status code. After how many requests you want this condition to kick in? - After how many requests throwing the concerned status code you want this Auto-Heal rule to start writing/capturing relevant data. What should be the status code for these requests? - Mention the status code here. What should be the sub-status code for these requests? - Mention the sub-status code here, if any, else you can leave this blank. What should be the win32-status code for these requests? - Mention the win32-status code here, if any, else you can leave this blank. What is the time interval (in seconds) in which the above condition should be met? - In how many seconds, the above defined status code should occur. What is the request path (leave blank for all requests)? - If there is a specific URL which is throwing that status code, you can add that in this section or leave it as blank. Add the values according to your scenario and click on "Ok" In the below screenshot, the rule is set for this example "1 request throwing HTTP 500 status code in 60 seconds should trigger this rule" After adding the above information, you can follow the Steps 6, 7 ,8, 9 from the first scenario (Slow Requests) and the Auto-Heal rule for the status code will become active and monitor for this performance issue. Auto-Heal rule to capture Memory dump for High Memory usage: For this scenario, Steps 1, 2, 3 will remain the same as above (from the Slow requests scenario). There will be following changes: 1. Select Memory Limit and click on Configure Private Bytes rule: 2. According to your application's memory usage, add the Private bytes in KB at which this rule should be triggered: In the below screenshot, the rule is set for this example "The application process using 2000000 KB (~2 GB) should trigger this rule" Click on "Ok" 3. In Configure Actions, select Custom Action and click on Memory Dump: 4. The tool options provide three choices: CollectKillAnalyze: If this option is selected, the tool will collect the data, analyze and generate the report and recycle the process. CollectLogs: If this option is selected, the tool will collect the data only. It will not analyze and generate the report and recycle the process. Troubleshoot: If this option is selected, the tool will collect the data and analyze and generate the report, but it will not recycle the process. Select the option, according to your scenario: 5. For the memory dumps/reports to get saved, you will have to select either an existing Storage Account or will have to create a new one: Click on Select: Create a new one or choose existing: 6. Once the storage account is set, click on "Save". Review the rule settings and click on "Save". Clicking on "Save" will cause a restart as this is a configuration level change and for this to get in effect a restart is required. So, it is advised to make such changes in non-business hours. Best Practices for Using Auto-Heal Start with Conservative Rules: Avoid overly aggressive auto-restarts to prevent unnecessary disruptions. Monitor Performance Trends: Use Azure Monitor to correlate Auto-Heal events with performance metrics. Regularly Review Logs: Periodically analyze collected logs and dumps to fine-tune your Auto-Heal strategy. Combine with Application Insights: Leverage Application Insights for end-to-end monitoring and deeper diagnostics. Conclusion Auto-Heal in Azure App Service is a powerful tool that not only helps maintain application stability but also provides critical diagnostic data when performance issues arise. By proactively setting up Auto-Heal rules and leveraging its diagnostic capabilities, you can minimize downtime and streamline troubleshooting efforts. Have you used Auto-Heal in your application? Share your experiences and insights in the comments! Stay tuned for more Azure tips and best practices!426Views2likes0CommentsCapture .NET Profiler Trace on the Azure App Service platform
Summary The article provides guidance on using the .NET Profiler Trace feature in Microsoft Azure App Service to diagnose performance issues in ASP.NET applications. It explains how to configure and collect the trace by accessing the Azure Portal, navigating to the Azure App Service, and selecting the "Collect .NET Profiler Trace" feature. Users can choose between "Collect and Analyze Data" or "Collect Data only" and must select the instance to perform the trace on. The trace stops after 60 seconds but can be extended up to 15 minutes. After analysis, users can view the report online or download the trace file for local analysis, which includes information like slow requests and CPU stacks. The article also details how to analyze the trace using Perf View, a tool available on GitHub, to identify performance issues. Additionally, it provides a table outlining scenarios for using .NET Profiler Trace or memory dumps based on various factors like issue type and symptom code. This tool is particularly useful for diagnosing slow or hung ASP.NET applications and is available only in Standard or higher SKUs with the Always On setting enabled. In this article How to configure and collect the .NET Profiler Trace How to download the .NET Profiler Trace How to analyze a .NET Profiler Trace When to use .NET Profilers tracing vs. a memory dump The tool is exceptionally suited for scenarios where an ASP.NET application is performing slower than expected or gets hung. As shown in Figure 1, this feature is available only in Standard or higher Stock Keeping Unit (SKU) and Always On is enabled. If you try to configure .NET Profiler Trace, without both configurations the following messages is rendered. Azure App Service Diagnose and solve problems blade in the Azure Portal error messages Error – This tool is supported only on Standard, Premium, and Isolated Stock Keeping Unit (SKU) only with AlwaysOn setting enabled to TRUE. Error – We determined that the web app is not "Always-On" enabled and diagnostic does not work reliably with Auto Heal. Turn on the Always-On setting by going to the Application Settings for the web app and then run these tools. How to configure and collect the .NET Profiler Trace To configure a .NET Profiler Trace access the Azure Portal and navigate to the Azure App Service which is experiencing a performance issue. Select Diagnose and solve problems and then the Diagnostic Tools tile. Azure App Service Diagnose and solve problems blade in the Azure Portal Select the "Collect .NET Profiler Trace" feature on the Diagnostic Tools blade and the following blade is rendered. Notice that you can only select Collect and Analyze Data or Collect Data only. Choose the one you prefer but do consider having the feature perform the analysis. You can download the trace for offline analysis if necessary. Also notice that you need to **select the instance** on which you want to perform the trace. In the scenario, there is only one, so the selection is simple. However, if your app runs on multiple instances, either select them all or if you identify a specific instance which is behaving slowly, select only that one. You realize the best results if you can isolate a single instance enough so that the request you sent is the only one received on that instance. However, in a scenario where the request or instance is not known, the trace adds value and insights. Adding a thread report provides list of all the threads in the process is also collected at the end of the profiler trace. The thread report is useful especially if you are troubleshooting hung processes, deadlocks, or requests taking more than 60 seconds. This pauses your process for a few seconds until the thread dump is generated. CAUTION: a thread report is NOT recommended if you are experiencing High CPU in your application, you may experience issues during trace analysis if CPU consumption is high. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace blade in the Azure Portal There are a few points called out in the previous image which are important to read and consider. Specifically the .NET Profiler Trace will stop after 60 seconds from the time that it is started. Therefore, if you can reproduce the issue, have the reproduction steps ready before you start the profiling. If you are not able to reproduce the issue, then you may need to run the trace a few times until the slowness or hang occurs. The collection time can be increased up to 15 minutes (900 seconds) by adding an application setting named IIS_PROFILING_TIMEOUT_IN_SECONDS with a value of up to 900. After selecting the instance to perform the trace on, press the Collect Profiler Trace button, wait for the profiler to start as seen here, then reproduce the issue or wait for it to occur. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace status starting window After the issue is reproduced the .NET Profiler Trace continues to the next step of stopping as seen here. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace status stopping window Once stopped, the process continues to the analysis phase if you selected the Collect and Analyze Data option, as seen in the following image, otherwise you are provided a link to download the file for analysis on your local machine. The analysis can take some time, so be patient. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace status analyzing window After the analysis is complete, you can either view the Analysis online or download the trace file for local development. How to download the .NET Profiler Trace Once the analysis is complete you can view the report by selecting the link in the Reports column, as seen here. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace status complete window Clicking on the report you see the following. There is some useful information in this report, like a list of slow requests, Failed Requests, Thread Call stacks, and CPU stacks. Also shown is a breakdown of where the time was spent during the response generation into categories like Application Code, Platform, and Network. In this case, all the time is spent in the Application code. Azure App Service Diagnose and solve problems, Collect .NET Profiler Trace review the Report To find out specifically where in the Application Code this request performs the analysis of the trace locally. How to analyze a .NET Profiler Trace After downloading the network trace by selecting the link in the Data column, you can use a tool named Perf View which is downloadable on GitHub here. Begin by opening Perf View and double-clicking on the ".DIAGSESSION" file, after some moments expand it to render the Event Trace Log (ETL) file, as shown here. Analyze Azure App Service .NET Profiler Trace with Perf View Double-click on the Thread Time (with startStop Activities) Stacks which open up a new window similar to shown next. If your App Service is configured as out-of-process select the dotnet process which is associated to your app code. If your App Service is in-process select the w3wp process. Analyze Azure App Service .NET Profiler Trace with Perf View, dotnet out-of-process Double-click on dotnet and another window is rendered, as shown here. From the previous image, .NET Profiler Trace reviews the Report, it is clear where slowness is coming from, find that in the Name column or search for it by entering the page name into the Find text box. Analyze Azure App Service .NET Profiler Trace with Perf View, dotnet out-of-process, method, and class discovery Once found right-click on the row and select Drill Into from the pop-up menu, shown here. Select the Call Tree tab and the reason for the issue renders showing which request was performing slow. Analyze Azure App Service .NET Profiler Trace with Perf View, dotnet out-of-process, root cause This example is relatively. As you analyze more performance issues using Perf View to analyze a .NET Profiler Trace your ability to find the root cause of more complicated performance issues can be realized. When to use .NET Profilers tracing vs. a memory dump That same issue is seen in a memory dump, however there are some scenarios where a .NET Profile trace would be best. Here is a table, Table 1, which describes scenarios for when to capture a .NET profile trace or to capture a memory dump. Issue Type Symptom Code Symptom Stack Startup Issue Intermittent Scenario Performance 200 Requests take 500 ms to 2.5 seconds, or takes <= 60 seconds ASP.NET/ASP.NET Core No No Profiler Performance 200 Requests take > 60 seconds & < 230 seconds ASP.NET/ASP.NET Core No No Dump Performance 502.3/500.121/503 Requests take >=120 to <= 230 seconds ASP.NET No No Dump, Profiler Performance 502.3/500.121/503 Requests timing out >=230 ASP.NET/ASP.NET Core Yes/No Yes/No Dump Performance 502.3/500.121/503 App hangs or deadlocks (ex: due to async anti-pattern) ASP.NET/ASP.NET Core Yes/No Yes/No Dump Performance 502.3/500.121/503 App hangs on startup (ex: caused by nonasync deadlock issue) ASP.NET/ASP.NET Core No Yes/No Dump Performance 502.3/500.121 Request timing out >=230 (time out) ASP.NET/ASP.NET Core No No Dump Availability 502.3/500.121/503 High CPU causing app downtime ASP.NET No No Profiler, Dump Availability 502.3/500.121/503 High Memory causing app downtime ASP.NET/ASP.NET Core No No Dump Availability 500.0[121]/503 SQLException or Some Exception causes app downtime ASP.NET No No Dump, Profiler Availability 500.0[121]/503 App crashing due to fatal exception at native layer ASP.NET/ASP.NET Core Yes/No Yes/No Dump Availability 500.0[121]/503 App crashing due to exit code (ex: 0xC0000374) ASP.NET/ASP.NET Core Yes/No Yes/No Dump Availability 500.0 App begin nonfatal exceptions (during a context of a request) ASP.NET No No Profiler, Dump Availability 500.0 App begin nonfatal exceptions (during a context of a request) ASP.NET/ASP.NET Core No Yes/No Dump Table 1, when to capture a .NET Profiler Trace or a Memory Dump on Azure App Service, Diagnose and solve problems Use this list as a guide to help decide how to approach the solving of performance and availability applications problems which are occurring in your application source code. Here are some descriptions regarding the column heading. - Issues Type – Performance means that a request to the app is responding or processing the response but not at a speed in which it is expected to. Availability means that the request is failing or consuming more resources than expected. - Symptom Code – the HTTP Status and/or sub status which is returned by the request. - Symptom – a description of the behavior experienced while engaging with the application. - Stack – this table targets .NET, specifically ASP.NET, and ASP.NET Core applications. - Startup Issue – if "No" then the Scenario can or should be used, "No" represents that the issue is not at startup. If "Yes/No" it means the Scenario is useful for troubleshooting startup issues. - Intermittent – if "No" then the Scenario can or should be used, "No" means the issue is not intermittent or that it can be reproduced. If "Yes/No" it means the Scenario is useful if the issue happens randomly or cannot be reproduced. Meaning that the tool can be set to trigger on a specific event or left running for a specific amount of time until the exception happens. - Scenario – "Profiler" means that the collection of a .NET Profiler Trace would be recommended. "Dump" means that a memory dump would be your best option. If both are provided, then both can be useful when the given symptoms and system codes are present. You might find the videos in Table 2 useful which instruct you how to collect and analyze a memory dump or .NET Profiler Trace. Product Stack Hosting Symptom Capture Analyze Scenario App Service Windows in High CPU link link Dump App Service Windows in High Memory link link Dump App Service Windows in Terminate link link Dump App Service Windows in Hang link link Dump App Service Windows out High CPU link link Dump App Service Windows out High Memory link link Dump App Service Windows out Terminate link link Dump App Service Windows out Hang link link Dump App Service Windows in High CPU link link Dump Function App Windows in High Memory link link Dump Function App Windows in Terminate link link Dump Function App Windows in Hang link link Dump Function App Windows out High CPU link link Dump Function App Windows out High Memory link link Dump Function App Windows out Terminate link link Dump Function App Windows out Hang link link Dump Azure WebJob Windows in High CPU link link Dump App Service Windows in High CPU link link .NET Profiler App Service Windows in Hang link link .NET Profiler App Service Windows in Exception link link .NET Profiler App Service Windows out High CPU link link .NET Profiler App Service Windows out Hang link link .NET Profiler App Service Windows out Exception link link .NET Profiler Table 2, short video instructions on capturing and analyzing dumps and profiler traces Here are a few other helpful videos for troubleshooting Azure App Service Availability and Performance issues: View Application EventLogs Azure App Service Add Application Insights To Azure App Service Prior to capturing and analyzing memory dumps, consider viewing this short video: Setting up WinDbg to analyze Managed code memory dumps and this blog post titled: Capture memory dumps on the Azure App Service platform. Question & Answers - Q: What are the prerequisites for using the .NET Profiler Trace feature in Azure App Service? A: To use the .NET Profiler Trace feature in Azure App Service, the application must be running on a Standard or higher Stock Keeping Unit (SKU) with the Always On setting enabled. If these conditions are not met, the tool will not function, and error messages will be displayed indicating the need for these configurations. - Q: How can you extend the default collection time for a .NET Profiler Trace beyond 60 seconds? A: The default collection time for a .NET Profiler Trace is 60 seconds, but it can be extended up to 15 minutes (900 seconds) by adding an application setting named IIS_PROFILING_TIMEOUT_IN_SECONDS with a value of up to 900. This allows for a longer duration to capture the necessary data for analysis. - Q: When should you use a .NET Profiler Trace instead of a memory dump for diagnosing performance issues in an ASP.NET application? A: A .NET Profiler Trace is recommended for diagnosing performance issues where requests take between 500 milliseconds to 2.5 seconds or less than 60 seconds. It is also useful for identifying high CPU usage causing app downtime. In contrast, a memory dump is more suitable for scenarios where requests take longer than 60 seconds, the application hangs or deadlocks, or there are issues related to high memory usage or app crashes due to fatal exceptions. Keywords Microsoft Azure, Azure App Service, .NET Profiler Trace, ASP.NET performance, Azure debugging tools, .NET performance issues, Azure diagnostic tools, Collect .NET Profiler Trace, Analyze .NET Profiler Trace, Azure portal, Performance troubleshooting, ASP.NET application, Slow ASP.NET app, Azure Standard SKU, Always On setting, Memory dump vs profiler trace, Perf View analysis, Azure performance diagnostics, .NET application profiling, Diagnose ASP.NET slowness, Azure app performance, High CPU usage ASP.NET, Azure app diagnostics, .NET Profiler configuration, Azure app service performance262Views1like0CommentsBuilding new AI skills for developers
For this post, we’re focusing on learning new AI skills. We explore resources that will help developers take their AI skills (and their applications) to the next level. Whether you’re new to AI and don’t know where to get started, or you’re experienced but want to advance your skillset with some new tools and capabilities, we have resources that will get you there. Join a challenge, find a Microsoft Learn path, get info on the latest tools and updates, watch in-depth videos, join a live event for hands-on learning, and more. How to develop AI Apps and Agents in Azure: A Visual Guide Move beyond proof-of-concept and build production-ready AI apps and agents in Azure. This visual guide walks you through the essential steps and decisions for building intelligent apps in Azure. Join the Powerful Devs Challenge and level up your Power Platform skills Join the Powerful Devs Challenge and take your developer skills to the next level! Learn how to build, extend, secure, and deploy enterprise-ready solutions with Power Platform. Now through March 28, 2025. Microsoft: Reactor: Python + AI Use Python to build applications that support Gen AI. Join Python + AI—a live 6-part Reactor series—to learn how. Sessions will include live examples and code samples. Sessions are live throughout March and available on demand. Generative AI for Beginners .NET Edition The “Generative AI for Beginners .NET" course on GitHub is designed to help .NET developers dive into the world of Gen AI. It features short 5-10 minute videos and code samples, offering an easy way to start adding GenAI to your .NET projects. GitHub Copilot Agent Mode: Build an iOS App in Minutes Discover the power of Agent Mode in VS Code Insiders. Watch to see how you can build a fully functional iOS app from scratch in minutes. Let AI handle everything from generating code to fixing build errors. Start your AI learning journey Ready to get started with AI but don’t know where to begin? The AI learning hub from Microsoft Learn is packed with skilling resources, organized around roles, to help you build practical skills you can use right away. Let's Learn .NET: GitHub Copilot Discover the power of Copilot and .NET. Watch this Let’s Learn .NET workshop on demand to learn about GitHub Copilot, Copilot Chat, and AI-powered coding. Master the basics of Copilot, explore prompt engineering. and learn essential best practices. Bells and whistles: Building with Microsoft Copilot Studio Don’t know how to start building an agent in Microsoft Copilot Studio? Watch the Building with Copilot Studio series to explore the different capabilities of building agents with Copilot Studio. Get Started with GitHub Copilot in VS Code Use GitHub Copilot in Visual Studio Code to write better code faster. This video will show you how. AI Agents for Beginners AI agents for beginners! This free 10-part course on GitHub will get you started building AI agents from concept to code. Evolve with generative AI: Operationalize your AI solutions with fine-tuning and prompt flow This Microsoft Learn Plan will guide you through the process of managing and evolving your Gen AI solutions. Learn how to use a prompt flow, collaborate with others through hubs and projects, and integrate fine-tuned models. Sip and Sync with Azure Explore real AI and cloud use cases in the Sip and Sync with Azure video series. Watch to learn how customers use AI and cloud solutions to solve real-world business problems. Official plan: Accelerate gen AI model selection and evaluation with Azure AI Foundry This Official Plan from Microsoft Learn is designed to guide you through the process of selecting and applying the best Gen AI models for your needs using Azure AI Foundry. Work through this structured learning journey at your pace and build critical skills. A look at the new Copilot Next Edit Suggestions preview GitHub Copilot has 3 exciting new preview capabilities: Next Edit Suggestions, Agent Mode for Copilot Edits, and vision support. Take a closer look at Next Edit Suggestions and learn about the latest step in intelligent code completions. Microsoft Reactor: Model Mondays How well do you know your AI models? With thousands available, how do you choose the best one for your project? Model Mondays can help. Each week, this series will dig into a different model with the experts who know it best. Architecture Recipes for AI-Powered Applications Build intelligent apps at a live Reactor event near you. Explore practical examples and best practices as you learn how to integrate machine learning models, data pipelines, and cloud services. GitHub Copilot for Azure: 6 Must-Try features Supercharge your Azure game right within GitHub Copilot? Watch these short videos to quickly learn about 6 must-try features in GitHub Copilot for Azure. RAG Time: Ultimate Guide to Mastering RAG Become a master of Retrieval-Augmented Generation (RAG). This new series for developers will help you unlock the full potential of RAG with exert level discussions breaking along with code samples and step-by-step guides. New episodes on Wednesdays, March 5 - April 2. Microsoft Learn Collection: Microsoft 365 Copilot extensibility Want to extend Microsoft 365 Copilot? This collection of resources from Microsoft Learn has everything you need to know to extend Microsoft 365 Copilot with agents, Microsoft Graph connectors, and more. Find a learning path and get started. Introducing the Adaptive Cards documentation hub and new Adaptive Cards updates Learn about the latest Adaptive Cards updates and the new Adaptive Cards documentation hub. Discover how Adaptive Cards can transform your apps with interactive experiences that streamline workflows. Use DeepSeek R1 on your GPU to power custom engine agents Learn how to use the DeepSeek R1 (hosted locally on your GPU) to power a custom engine agent built with Teams Toolkit and Teams AI Library. POSETTE: An Event for Postgres 2025 schedule announced Get details about POSETTE, a free digital developer event organized by the Postgres team at Microsoft. Check out the schedule and speakers for this year’s event, taking place June 10-12, 2025. JDConf 2025: Code the Future with AI Get ready for JDConf 2025, Microsoft's annual event for Java developers. Learn about building modern apps in the cloud, integrating AI, using AI-assisted dev tools, and more. This year’s event will take place April 9-10, 2025. VS Code + GitHub Copilot Release Party Join the VS Code + GitHub Copilot release party (April 16, 2025). Join the Visual Studio Code and GitHub Copilot teams for a deep dive into the latest features and Q&A about the March release. More News and Resources from around Microsoft Introducing Copilot Next Edit Suggestions (preview) in VS Code New: Semantic Ranker Solution Accelerator for PostgreSQL New: GraphRAG Solution Accelerator for PostgreSQL Preview: Azure AI Agent Service Startup Spotlight Get Started with Copilot Free in VS Code Raising the bar for RAG excellence: New performance benchmarks Automate Dev Environments with Microsoft Dev Box and Teams Customizations Dev Proxy: Simulate APIs Microsoft 365 Copilot Chat Microsoft Copilot Studio: Enabling agents in Microsoft 365 Copilot Chat371Views0likes0CommentsDo more with Copilot and agents
For February, we’re delving deep into Copilots and AI agents. We have live events and learning resources that will help developers get started and do more so you can take your productivity to a new level. Learn about tools for creating agents, find out how to use GitHub Copilot to develop apps more quickly, build intelligent apps with .NET, start creating customized experiences for Microsoft Teams, and more. GitHub Copilot Bootcamp Join the GitHub Copilot Bootcamp to deep dive into the tools and skills you need to supercharge your development productivity and with GitHub Copilot. This is a 4-part live series happening February 4–13, 2025. AI agents — what they are, and how they’ll change the way we work What are AI agents? Discover what agents are, how they work autonomously around-the-clock, and how you can build agents specific to your business needs. Microsoft 365 Copilot Developer Camp Start building agents for Microsoft 365 Copilot. Watch Microsoft 365 Copilot Developer Camp videos on demand, work through guided hands-on labs, and explore more resources to help you learn how to build your own agents. Getting started with AI Agents Azure AI Agent Service lets you build software that will work to achieve a specified goal without you knowing exactly what steps it will take. Join this session to learn how you can automate tasks that were previously too complex to be easily automated. Preview the GitHub Copilot extension for Teams Toolkit Discover a more powerful way to build Microsoft Teams apps and customize Microsoft 365 Copilot. Introducing the GitHub Copilot for Teams Toolkit (preview)—your new companion in VS Code, Visual Studio, and GitHub.com. Find practical resources on the Copilot learning hub on Microsoft Learn We’ve got curated content on Microsoft Copilot for technical professionals. Learn how to use AI technology, create custom experiences, and increase productivity. Generative AI Level Up Explore the cutting edge of app development with the Microsoft Reactor “Generative AI Level Up Tuesdays” series. Delve into the basics of Gen AI, learn about building AI agents, find out how responsible AI tooling helps mitigate risks, and more. Simplify development with the new Microsoft 365 Agents SDK Want to simplify your agent development? The Microsoft 365 Agents SDK brings together core components making it easier to build agents and publish them to Microsoft 365 Copilot, Teams, the web, and other channels. Learn, collaborate, and build your skills with Microsoft Fabric experts and peers The Microsoft Fabric Community Conference (FabCon) returns to Las Vegas March 31 to April 2, 2025, packed with breakout sessions and technical deep dives covering data, analytics, and AI. Sign up now with code MCUST to save $150. Introducing the new .NET AI Applications page Have you seen the new .NET AI Applications page? Explore videos, documentation, SDKs, AI libraries and other essential resources to help you build intelligent solutions using C#, OpenAI, and Azure. AI learning hub Visit the AI learning hub, a place to learn new AI skills. Get started with curated plans and resources designed around business and technical roles. Build AI agents, learn best practices, explore basic concepts, and dig into more advanced topics. Build AI Agents & Apps FAST with Azure AI Foundry Looking for a fast way to start building AI agents and applications? This video shows how to use Azure AI Foundry for super fast results. Learn about AI Foundry, AI app templates, the decision tree, and how to get started. What is Azure AI Agent Service? Learn about Azure AI Agent Service, a fully managed service designed for securely building, deploying, and scaling AI agents without needing to manage compute and storage resources. Discover what you can do with just a few lines of code. AI agents in Azure Cosmos DB Explore conceptual overviews and detailed implementation samples for AI agents. This Microsoft Learn article offers a deep-dive overview, looking at types of agents, frameworks, and code samples. Microsoft JDConf 2025 Register for JDConf 2025 and get ready to code the future with AI. Microsoft's annual event for Java developers will take place April 9-10, offering three separate live streams to cover different regions. Explore tools and skills for building modern apps in the cloud and integrating AI. Other news and resources from around Microsoft Architecture Recipes for AI-Powered Applications https://aka.ms/DevCal_Feb25_05 What’s new in AI Toolkit for Visual Studio Code January 2025 Updates https://aka.ms/DevCal_Feb25_18 On demand webinar: Secure Software Development from Code to Cloud with DevSecOps and AI https://aka.ms/DevCal_Feb25_176.1KViews1like1CommentCustom scaling on Azure Container Apps based on Redis Streams
ACA's autoscaling feature internally leverages KEDA and gives you the ability to configure the number of replicas to deploy based on rules (event triggers). Apart from HTTP and TCP rule based scaling, container apps also support custom rules giving it the flexibility and opening up a lot more configuration options since all of KEDA's event-based scalers are supported.6.1KViews3likes2CommentsEnhancing Security for Azure Container Apps with Aqua Security
Azure Container Apps (ACA) is a developer-first serverless platform that allows you to run scalable containerized workloads at any scale. Being serverless provides inherent security benefits by reducing the attack surface, but it also presents some unique challenges for any security solution. Hence, we’re happy to announce that our partner, Aqua has just certified Azure Container Apps for their suite of security solutions. Azure Container Apps: Built-In Security Features Due to its purpose-built nature ACA offers several built-in security features that help protect your containerized applications: Isolation: ACA runs your workload without the need for root access to the underlying host. Additionally, it’s trivial and requires minimal overhead to isolate different teams in their own environments without the need to painfully cordon off each team via Kubernetes namespaces. Network Security: ACA supports virtual network integration, allowing you to control inbound and outbound traffic to your applications on a both a per app basis as well as for an entire environment all at once. Additionally, we provide protection against common layer-7 vulnerabilities such as redirection attacks. Managed Identity: ACA integrates with Azure Active Directory, enabling secure access to other Azure services without managing credentials. While these features provide a solid foundation, securing containerized workloads requires a comprehensive approach that addresses the entire lifecycle of your applications. This is where Aqua’s suite of tools excels. Elevating ACA's Security Posture using Aqua Aqua Security is a certified security solution for ACA, offering a full-lifecycle approach to securing your containerized applications. Here’s how Aqua enhances ACA's security capabilities: Supply Chain Security: Aqua scans container images for tampering and potential supply chain attacks, ensuring that only verified and secure images are deployed. Comprehensive Image Scanning: Aqua scans container images in Azure Container Registry (ACR) and CI/CD pipelines for vulnerabilities, misconfigurations, malware, and embedded secrets, enabling developers to address issues early. Image Assurance Policies: Aqua enforces policies to ensure that only compliant images are deployed, minimizing risks and ensuring adherence to security and compliance standards. Agentless Discovery and Scanning: Aqua automatically discovers and scans all running services and assets, providing broad visibility into your ACA workloads. Runtime Protection with MicroEnforcer: Aqua's MicroEnforcer provides non-invasive runtime security, detecting and preventing threats such as cryptocurrency mining, reverse shell execution, and unauthorized access. By leveraging Aqua's security solutions, organizations can confidently meet the most stringent security requirements for their ACA workloads. For more information on how to use Aqua's tooling with ACA, visit the Aqua blog: Securing Azure Container Apps505Views0likes0CommentsLearn New Skills in the New Year
New year’s resolution: Start writing better code faster in 2025. Kick off the new year by learning new developer skills and elevate your career to the next level. In this post, we explore learning resources and live events that will help you build critical skills and get started with cutting-edge technologies. Learn how to build custom agents, code intelligent apps with familiar tools, discover new possibilities in .NET 9, use Copilot for testing and debugging, and more. Plus, get details about using GitHub Copilot in Visual Studio Code—for free! New AI for Developers page Check out the new AI for Developers page. It's packed with free GitHub courses on building apps, machine learning, and mastering GitHub Copilot for paired programming. Learn your way and skill up for what's next in AI. Use GitHub Copilot in Visual Studio Code for free Did you hear the news? You can now use GitHub Copilot in Visual Studio Code for free. Get details about the new Copilot Free plan and add Copilot to your developer toolbox. What is Copilot Studio? Have questions about Copilot Studio? This article from Microsoft Learn covers all the basics you need to know about Copilot Studio—the low-code tool for easily building agents and extending Microsoft 365 Copilot. From C# to ChatGPT: Build Generative AI Solutions with Azure Combine your C# skills with the cutting-edge power of ChatGPT and Azure OpenAI Service. This free learning path introduces you to building GenAI solutions, using REST APIs, SDKs, and Azure tools to create more intelligent applications. Register for the Powerful Devs Conference + Hackathon Register for the Powerful Devs Conference + Hackathon (February 12-28, 2025) and get more out of Power Platform. This one-day online conference is followed by a 2-week hackathon focused on building intelligent applications with less effort. Code the future with Java and AI: RSVP for Microsoft JDConf 2025 today Get ready for the JDConf 2025—Microsoft's annual event for Java developers. Taking place April 9-10, this year’s event will have three separate live streams to cover different regions. Join to explore tools and skills for building modern apps in the cloud and integrating AI. Build custom agents for Microsoft Teams Learn how to build custom agents for Microsoft Teams. This free learning path will teach you about different copilot stacks, working with Azure OpenAI, building a custom engine agent. Start building intelligent Microsoft Teams apps using the LLMs and AI components. Microsoft Learn: Debug your app with GitHub Copilot in Visual Studio Debug more efficiently using GitHub Copilot. This Microsoft Learn article shows you how. Discover how Copilot will answer detailed questions about your code and provide bug fixes. Make Azure AI Real: Watch Season 2 Elevate your AI game with Make Azure AI Real on demand. Season 2 digs into the latest Azure AI advancements, with practical demos, code samples, and real-world use cases. GitHub Copilot Bootcamp Streamline your workflow with GitHub Copilot—craft more effective prompts and automate repetitive tasks like testing. This GitHub Copilot Bootcamp is a 4-part live streaming series that will help you master GitHub Copilot. 10 Days of GenAI – Gift Guide Edition Start building your own Gen AI application. These short videos outline 10 steps for creating your app—choose a model, add functions, fine tune responses, and more. Extend Microsoft 365 Copilot with declarative agents using Visual Studio Code Check out this new learning path from Microsoft Learn to discover how you can extend Microsoft 365 Copilot with declarative agents using VS Code. Learn about declarative agents and how they work. Developer's guide to building your own agents Want to build your own agents? Watch this Ignite session on demand for a look at the new agent development tools. Find out how to create agents built on Microsoft 365 Copilot or your custom AI engine. Master distributed application development with .NET Aspire Get started with .NET Aspire—an opinionated, cloud-ready stack for building distributed applications with .NET. This series covers everything from setup to deployment. Start your journey toward mastering distributed app development. Learn: What's new in .NET 9 Discover what's new in .NET 9. Learn about new features for AI, improvements for building cloud-native apps, performance enhancements, updates to C#, and more. Read the overview and get started with .NET 9. Become a .NET AI engineer using the OpenAI library for .NET Use your .NET skills to become an AI engineer. With the OpenAI library, .NET developers can quickly master critical AI skills and apply them to real world apps. Read the blog to learn more about the OpenAI library for .NET. Test like a pro with Playwright and GitHub Copilot Supercharge your testing using Playwright and GitHub Copilot. Watch this in-depth demo and discover how you can easily create end-to-end tests using Playwright's powerful built-in code generator. Other news and resources from around Microsoft · Microsoft Learn: Why and how to adopt AI in your organization · Microsoft Learn: Learn to use Copilot in Microsoft Fabric · AI Toolkit for Visual Studio Code: Update highlights · Teams Toolkit for Visual Studio Code update · RAG Deep Dive: Live streams · Learn Together: SQL database in Fabric · Become an AI security expert using OpenAI with Azure Managed Identity · Deploy, monitor, and manage development resources with Microsoft Dev Box · Microsoft Playwright testing · Introduction to artificial intelligence and Azure AI services · Azure AI-900 Fundamentals Training event series · Leveraging cloud-native infra for your intelligent apps · Platform engineering with GitHub · Extend declarative agents for Microsoft 365 Copilot with API plugins using Visual Studio Code · Introducing the Microsoft 365 Agents SDK · Azure Live Q&A events · Get started with multimodal parsing for RAG using GPT-4o, Azure AI Search, and LlamaParse3.3KViews2likes0CommentsConnection Between Web App and O365 Resources: Using SharePoint as an Example
TOC Introduction [not recommended] Application permission [not recommended] Delegate permission with Device Code Flow Managed Identity Multi-Tenant App Registration Restrict Resources for Application permission References Introduction In late 2024, Microsoft Entra enforced MFA (Multi-Factor Authentication) for all user login processes. This change has caused some Web Apps using delegated permissions to fail in acquiring access tokens, thereby interrupting communication with O365 resources. This tutorial will present various alternative solutions tailored to different business requirements. We will use a Linux Python Web App as an example in the following sections. [not recommended] Application permission Traditionally, using delegated permissions has the advantages of being convenient, quick, and straightforward, without being limited by whether the Web App and Target resources (e.g., SharePoint) are in the same tenant. This is because it leverages the user identity in the SharePoint tenant as the login user. However, its drawbacks are quite evident—it is not secure. Delegated permissions are not designed for automated processes (i.e., Web Apps), and if the associated connection string (i.e., app secret) is obtained by a malicious user, it can be directly exploited. Against this backdrop, Microsoft Entra enforced MFA for all user login processes in late 2024. Since delegated permissions rely on user-based authentication, they are also impacted. Specifically, if your automated processes originally used delegated permissions to interact with other resources, they are likely to be interrupted by errors similar to the following in recent times. AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000003-0000-0000-c000-000000000000' The root cause lies in the choice of permission type. While delegated permissions can technically be used for automated processes, there is a more appropriate option—application permissions, which are specifically designed for use in automated workflows. Therefore, when facing such issues, the quickest solution is to create a set of application permissions, align their settings with your previous delegated permissions, and then update your code to use the new app ID and secret to interact with the target resource. This method resolves the issue caused by the mandatory MFA process interruption. However, it is still not entirely secure, as the app secret, if obtained by a malicious user, can be exploited directly. Nonetheless, it serves as a temporary solution while planning for a large-scale modification or refactor of your existing system. [not recommended] Delegate permission with Device Code Flow Similarly, here's another temporary solution. The advantage of this approach is that you don't even need to create a new set of application permissions. Instead, you can retain the existing delegated permissions and resolve the issue by integrating Device Code Flow. Let's see how this can be achieved. First, navigate to Microsoft Entra > App Registration > Your Application > Authentication, and enable "Allow public client flows". Next, modify your code to implement the following method to acquire the token. Replace [YOUR_TENANT_ID] and [YOUR_APPLICATION_ID] with your own values. import os, atexit, msal, sys def get_access_token_device(): cache_filename = os.path.join( os.getenv("XDG_RUNTIME_DIR", ""), "my_cache.bin" ) cache = msal.SerializableTokenCache() if os.path.exists(cache_filename): cache.deserialize(open(cache_filename, "r").read()) atexit.register(lambda: open(cache_filename, "w").write(cache.serialize()) if cache.has_state_changed else None ) config = { "authority": "https://login.microsoftonline.com/[YOUR_TENANT_ID]", "client_id": "[YOUR_APPLICATIOM_ID]", "scope": ["https://graph.microsoft.com/.default"] } app = msal.PublicClientApplication( config["client_id"], authority=config["authority"], token_cache=cache, ) result = None accounts = app.get_accounts() if accounts: print("Pick the account you want to use to proceed:") for a in accounts: print(a["username"]) chosen = accounts[0] result = app.acquire_token_silent(["User.Read"], account=chosen) if not result: flow = app.initiate_device_flow(scopes=config["scope"]) print(flow["message"]) sys.stdout.flush() result = app.acquire_token_by_device_flow(flow) if "access_token" in result: access_token = result["access_token"] return access_token else: error = result.get("error") if error == "invalid_client": print("Invalid client ID.Please check your Azure AD application configuration") else: print(error) Demonstrating the Process Before acquiring the token for the first time, there is no cache file named my_cache.bin in your project directory. Start the test code, which includes obtaining the token and interacting with the corresponding service (e.g., SharePoint) using the token. Since this is the first use, the system will prompt you to manually visit https://microsoft.com/devicelogin and input the provided code. Once the manual process is complete, the system will obtain the token and execute the workflow. After acquiring the token, the cache file my_cache.bin will appear in your project directory. This file contains the access_token and refresh_token. For subsequent processes, whether triggered manually or automatically, the system will no longer prompt for manual login. The cached token has a validity period of approximately one hour, which may seem insufficient. However, the acquire_token_silent function in the program will automatically use the refresh token to renew the access token and update the cache. Therefore, as long as an internal script or web job is triggered at least once every hour, the token can theoretically be used continuously. Managed Identity Using Managed Identity to enable interaction between an Azure Web App and other resources is currently the best solution. It ensures that no sensitive information (e.g., app secrets) is included in the code and guarantees that only the current Web App can use this authentication method. Therefore, it meets both convenience and security requirements for production environments. Let’s take a detailed look at how to set it up. Step 1: Setup Managed Identity You will get an Object ID for further use. Step 2: Enterprise Application for Managed Identity Your Managed Identity will generate a corresponding Enterprise Application in Microsoft Entra. However, unlike App Registration, where permissions can be assigned directly via the Azure Portal, Enterprise Application permissions must be configured through commands. Step 3: Log in to Azure via CloudShell Use your account to access Azure Portal, open a CloudShell, and input the following command. This step will require you to log in with your credentials using the displayed code: Connect-MgGraph -Scopes "Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All" Continue by inputting the following command to target the Enterprise Application corresponding to your Managed Identity that requires permission assignment: $PrincipalId = "<Your web app managed identity object id>" $ResourceId = (Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" | Select-Object -ExpandProperty Id) Step 4: Assign Permissions to the Enterprise Application Execute the following commands to assign permissions. Key Points: This example assigns all permissions with the prefix Sites.*. However, you can modify this to request only the necessary permissions, such as: Sites.Selected Sites.Read.All Sites.ReadWrite.All Sites.Manage.All Sites.FullControl.All If you do not wish to assign all permissions, you can change { $_.Value -like "*Sites.*" } to the specific permission you need, for example: { $_.Value -like "*Sites.Selected*" } Each time you modify the permission, you will need to rerun all the commands below. $AppRoles = Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" -Property AppRoles | Select -ExpandProperty AppRoles | Where-Object { $_.Value -like "*Sites.*" } $AppRoles | ForEach-Object { $params = @{ "PrincipalId" = $PrincipalId "ResourceId" = $ResourceId "AppRoleId" = $_.Id } New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $PrincipalId -BodyParameter $params } Step 5: Confirm Assigned Permissions If, in Azure Portal, you see a screen similar to this: (Include screenshot or example text for granted permissions) This means that the necessary permissions have been successfully assigned. Step 6: Retrieve a Token in Python In your Python code, you can use the following approach to retrieve the token: from azure.identity import ManagedIdentityCredential def get_access_token(): credential = ManagedIdentityCredential() token = credential.get_token("https://graph.microsoft.com/.default") return token.token Important Notes: When permissions are assigned or removed in the Enterprise Application, the ManagedIdentityCredential in your Python code caches the token for a while. These changes will not take effect immediately. You need to restart your application and wait approximately 10 minutes for the changes to take effect. Step 7: Perform Operations with the Token Finally, you can use this token to perform the desired operations. Below is an example of creating a file in SharePoint: You will notice that the uploader’s identity is no longer a person but instead the app itself, indicating that Managed Identity is indeed in effect and functioning properly. While this method is effective, it is limited by the inability of Managed Identity to handle cross-tenant resource requests. I will introduce one final method to resolve this limitation. Multi-Tenant App Registration In many business scenarios, resources are distributed across different tenants. For example, SharePoint is managed by Company (Tenant) B, while the Web App is developed by Company (Tenant) A. Since these resources belong to different tenants, Managed Identity cannot be used in such cases. Instead, we need to use a Multi-Tenant Application to resolve the issue. The principle of this approach is to utilize an Entra ID Application created by the administrator of Tenant A (i.e., the tenant that owns the Web App) that allows cross-tenant use. This application will be pre-authorized by future user from Tenant B (i.e., the administrator of the tenant that owns SharePoint) to perform operations related to SharePoint. It should be noted that the entire configuration process requires the participation of administrators from both tenants to a certain extent. Please refer to the following demonstration. This is a sequential tutorial; please note that the execution order cannot be changed. Step 1: Actions Required by the Administrator of the Tenant that Owns the Web App 1.1. In Microsoft Entra, create an Enterprise Application and select "Multi-Tenant." After creation, note down the Application ID. 1.2. In App Registration under AAD, locate the previously created application, generate an App Secret, and record it. 1.3. Still in App Registration, configure the necessary permissions. Choose "Application Permissions", then determine which permissions (all starting with "Sites.") are needed based on the actual operations your Web App will perform on SharePoint. For demonstration purposes, all permissions are selected here. Step 2: Actions Required by the Administrator of the Tenant that Owns SharePoint 2.1. Use the PowerShell interface to log in to Azure and select the tenant where SharePoint resides. az login --allow-no-subscriptions --use-device-code 2.2. Add the Multi-Tenant Application to this tenant. az ad sp create --id <App id get from step 1.1> 2.3. Visit the Azure Portal, go to Enterprise Applications, locate the Multi-Tenant Application added earlier, and navigate to Permissions to grant the permissions specified in step 1.3. Step 3: Actions Required by the Administrator of the Tenant that Owns the Web App 3.1. In your Python code, you can use the following method to obtain an access token: from msal import ConfidentialClientApplication def get_access_token_cross_tenant(): tenant_id = "your-sharepoint-tenant-id" # Tenant ID where the SharePoint resides (i.e., shown in step 2.1) client_id = "your-multi-tenant-app-client-id" # App ID created in step 1.1 client_secret = "your-app-secret" # Secret created in step 1.2 authority = f"https://login.microsoftonline.com/{tenant_id}" app = ConfidentialClientApplication( client_id, authority=authority, client_credential=client_secret ) scopes = ["https://graph.microsoft.com/.default"] token_response = app.acquire_token_for_client(scopes=scopes) return token_response.get("access_token") 3.2. Use this token to perform the required operations. Restrict Resources for Application permission Application permission, allows authorization under the App’s identity, enabling access to all SharePoint sites within the tenant, which could be overly broad for certain use cases. To restrict this permission to access a limited number of SharePoint sites, we need to configure the following settings: Actions Required by the Administrator of the Tenant that Owns SharePoint During the authorization process, only select Sites.Selected. (refer to Step 4 from Managed Identity, and Step 1.3 from Multu-tenant App Registration) Subsequently, configure access separately for different SharePoint sites. During the process, we will create a temporary App Registration to issue an access token, allowing us to assign specific SharePoint sites' read/write permissions to the target Application. Once the permission settings are completed, this App Registration can be deleted. Refer to the above images, we need to note down the App Registration's object ID and tenant ID. Additionally, we need to create an app secret and grant it the Application permission Sites.FullControl.All. Once the setup is complete, the token can be obtained using the following command. $tenantId = "<Your_Tenant_ID>" $clientId = "<Your_Temp_AppID>" $clientSecret = "<Your_Temp_App_Secret>" $scope = "https://graph.microsoft.com/.default" $url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $body = @{ grant_type = "client_credentials" client_id = $clientId client_secret = $clientSecret scope = $scope } $response = Invoke-RestMethod -Uri $url -Method Post -Body $body $accessToken = $response.access_token Before granting the write permission to the target application, even if the Application Permission already has the Sites.Selected scope, an error will still occur. Checking the current SharePoint site's allowed access list shows that it is empty. $headers = @{ "Authorization" = "Bearer $accessToken" "Content-Type" = "application/json" } Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/sites/<Your_SharePoint_Site>.sharepoint.com" -Headers $headers Next, we manually add the corresponding Application to the SharePoint site's allowed access list and assign it the write permission. $headers = @{ "Authorization" = "Bearer $accessToken" "Content-Type" = "application/json" } $body = @{ roles = @("write") grantedToIdentities = @( @{ application = @{ id = "<Your_Target_AppID>" displayName = "<Your_Target_AppName>" } } ) grantedToIdentitiesV2 = @( @{ application = @{ id = "<Your_Target_AppID>" displayName = "<Your_Target_AppName>" } } ) } | ConvertTo-Json -Depth 10 Invoke-RestMethod -Method Post -Uri "https://graph.microsoft.com/v1.0/sites/<Your_SharePoint_Site>.sharepoint.com/permissions" -Headers $headers -Body $body Rechecking the current SharePoint site's allowed access list confirms the addition. After that, writing files to the site will succeed, and you could delete the temp App Registration. References Microsoft will require MFA for all Azure users Acquire a token to call a web API using device code flow (desktop app) - Microsoft identity platform | Microsoft Learn Implement cross-tenant communication by using multitenant applications - Azure Architecture Center515Views1like0CommentsFrom Code to Cloud: Deploy Your Java Apps to Azure in Just 2 Steps!
Microsoft Azure is a great destination for Java applications, and our goal is to help Java developers easily onboard their applications to Azure. We understand that onboarding Java apps to Azure is not only about deploying Java apps but also includes the provisioning of dependent services like databases, messaging services as well as compute services like Azure Kubernetes Service, Azure Application Service, Azure Container Apps, etc. Java developers new to Azure often use either the Azure CLI or the Azure Portal to provision necessary Azure services. This requires learning many different CLI commands, different Portal experiences, and even different infrastructure-as code languages such as Bicep or Terraform. As my colleague Julia Muiruri wrote last week, Azure Developer CLI (AZD) helps developers quickly and efficiently onboard their applications to Azure. Today we are announcing the private preview of a set of new features designed specifically for Java developers. These features are implemented in the AZD CLI and exposed via a Visual Studio Code extension. Register now to try out these features and provide feedback. The new features in AZD simplify Azure onboarding for Java developers by providing a solution that requires only 2 steps to provision and deploy your application to Azure. New Java features in AZD This diagram illustrates the new features in AZD that simplify the developer experience for provisioning and deploying Java applications to Azure: Open your existing Java project in your preferred IDE. If you are using Maven, right click (the 1 st click) on the root pom.xml and choose “generate Azure deployment scripts”. Our tools will generate azure.yaml which declares all the necessary Azure services for your Java project and any connection information your Java application needs to connect to Azure services (such as a database or a messaging service). Next, right click (the 2 nd click) on azure.yaml and select “deploy to Azure”. As a result, all required Azure services will be provisioned automatically and your Java application will be deployed to the appropriate Azure compute service. To achieve this simplicity, AZD offers these key capabilities: An application-centric azure.yaml as the source definition to describe your application. There is no need to use different CLI commands, Bicep or Terraform scripts. Generate azure.yaml from any existing Java repository. You don’t need to write azure.yaml since AZD can analyze your Java project to auto detect resources and bindings between applications and dependent services. AZD will generate the necessary Bicep files from azure.yaml. If you need to view the Bicep files, AZD will synthesize these files for you to review. Getting started Let’s look at how to deploy a simple Spring application to Azure. The sample application is a to-do list management app, composed of three microservices: web, api and email services. When a user adds or updates a to-do item on the web page, the to-do item will be stored into MongoDB by the api service. For to-do items that are “due”, the api service will send messages into Azure Service Bus. These messages will be consumed by email service to send an email to you. This diagram shows the overall architecture and interaction relationship among the three services and their backing Azure services: MongoDB and Azure Service Bus. Putting it all together, to deploy this Spring application to Azure we need to: Provision Azure Cosmos DB for Mongo API. Provision Azure Service Bus. Provision the compute service to run the app, such as Azure Container Apps Deploy all three microservices onto the compute service with correct bindings to the DB or message service. Now let’s see how to do all this with just 2 clicks: Open VS code with this Spring project. Right click on the root pom.xml and choose “Generate Azure deployment Script”. azure.yaml will be generated under the root path with all necessary deployment artifacts declared inside. Right click on the azure.yaml and choose “Package, Provision and Deploy (up)” to trigger the overall provisioning and deployment. After deployment, you’ll see your dedicated resource group in the Azure Portal. In the resource group, you’ll see: Mongo DB: provisioned as Azure Cosmos DB service and running Azure Service Bus: provisioned as Azure Service Bus and running 3 Apps: deployed as Azure Container Apps all running inside a single Azure Container App environment. How to enroll in the private preview Are you a Java developer new to Azure and looking onboard your project or your team’s? Do you need to quickly set up an Azure environment for demonstrations, or aim to reduce development environment maintenance effort as the platform team? Azd might be the ideal solution for you. We encourage you to give it a try today! The new features are now in private preview. If interested, please register by scanning below QR Code or visiting https://aka.ms/azd-java-preview directly. We'll contact you within days. Your feedback will help us improve the public preview and GA releases.756Views3likes0Comments