azure paas
114 TopicsJDConf 2025: Announcing Keynote Speaker and Exciting Sessions on Java, Cloud, and AI
Microsoft JDConf 2025 is rapidly approaching and promises to be the must-attend event for Java developers, particularly those interested in the latest advancements in Java, Cloud and AI. This year, the conference will feature over 22 sessions and more than 10 hours of live streaming content for global audience, along with additional on-demand sessions available from April 9 to 10. The spotlight this year is on integrating AI into your development workflow with tools like Copilot, showcasing how these advancements are revolutionizing the coding landscape. Whether you are exploring application modernization, leveraging AI for intelligent apps, or optimizing Java deployments, JDConf has sessions for every interest. Code the future with AI Explore AI-driven Java innovation: Uncover the role of AI in enhancing Java application development on the cloud for greater efficiency and innovation. Livestream for all time zones: Live sessions scheduled to accommodate attendees from around the globe, ensuring no one misses out. Learn from Java experts and innovators: Discover the impact of diversity and open-source innovation in advancing the Java ecosystem. Global networking opportunity: Connect with Java professionals and community leaders worldwide to share knowledge and foster community growth. Free & accessible content: Enjoy all sessions without cost, available live and on-demand for ultimate flexibility. Earn rewards: Join the JDConf experience and earn Microsoft Rewards points. 🌟 RSVP now at JDConf.com !! ⭐ This year’s list of sessions Figure 1: Your quick guide to JDConf 2025: cheat sheet for the keynote and breakout sessions happening across three regions. Do not miss out on planning your perfect conference experience! Technical keynote: Code the future with Java & AI Amanda Silver, Microsoft | Josh Long, Broadcom | Lize Raes, Naboo.ai Join Amanda Silver, CVP and head of product, Microsoft Developer Division, as she takes the stage for the JDConf Opening Keynote, exploring how Java developers can harness the power of AI, cloud, and cutting-edge tools to accelerate development. From Visual Studio Code and GitHub Copilot to Cloud services, Amanda will showcase how Cloud and AI are transforming the developer experience, enabling teams to go from code to production faster than ever. She’ll also dive into the latest advancements in Java technologies, Microsoft's deep investments in the Java ecosystem, and the company's ongoing commitment to open-source innovation. Don't miss this opportunity to discover how Microsoft is empowering Java developers in the AI era! Session summaries by region Americas live stream - April 9, 8:30am – 12:30pm PDT Spring Boot: Bootiful Spring Boot: A DOGumentary by Josh Long will dive into Spring Boot 3.x and Java 21, exploring AI, modularity, and powerful optimizations like virtual threads, GraalVM, and AppCDS. AI Dev Experience: Boosting AI Developer Experience with Quarkus, LangChain4j, and Azure OpenAI by Daniel Oh will demonstrate how this trio streamlines development and powers intelligent apps. Spring AI: How to Build Agents with Spring AI by Adib Saikali will showcase building intelligent AI agents, covering key patterns like self-editing memory, task orchestration, & collaborative multi-agent systems. Jakarta EE 12: What Comes After Jakarta EE 11? Reza Rahman and Emily Jiang will share roadmap, contribution pathways, and key updates, including Security, Concurrency, Messaging, and new APIs. Deployment: Production Best Practices: Go from Dev to Delivered and Stay There by Mark Heckler will take Java apps from development to production with a focus on CI/CD, containerization, infrastructure as code, and cloud deployment. Cloud-native: Java Cloud-Native Shoot-Out: InstantOn vs CRaC vs Native Image by Yee-Kang Chang and Rich Hagarty will compare three emerging Java technologies; Liberty InstantOn, OpenJDK CRaC, and Native Image to determine which best supports fast start-up times and low resource usage in your cloud-native apps. AI-Driven Testing: Test Smarter, Not Harder: AI-Driven Test Development by Loiane Groner will demo how AI-powered tools like GitHub Copilot enhance TDD through automated test generation and improved test coverage, even for legacy code. Asia-Pacific live stream – April 10, 10:00am-1:30pm SGT LLMs integration: Building LLM Apps in Java with LangChain4j and Jakarta EE by Bazlur Rahman and Syed M Shaaf will demonstrates how to integrate large language models (LLMs) into Java apps, including techniques like retrieval-augmented generation (RAG) and embedding databases. Java Modernization: Modernize Java Apps Using GitHub Copilot Upgrade Assistant for Java by Nick Zhu will show how this tool can help modernize Java apps by automating refactoring, managing dependencies, and resolving version conflicts. Automated Refactoring: The State of AI in Large Scale Automated Refactoring by Jonathan Schneider will show how OpenRewrite’s Lossless Semantic Tree enhances AI-driven refactoring for accurate decision-making. Java Modernization: Cloud Migration of Java Applications Using Various Tools and Techniqueby Yoshio Terada will demo modernizing legacy apps with tools like VS Code, GitHub Copilot, and Azure Migrate. Java & AI: AI for Java Developers by Dan Vega will introduce AI for Java developers, covering machine learning, deep learning, and practical AI implementations such as chatbots, recommendation systems, and sentiment analysis. Hyperscale PaaS: Spring, Quarkus, Tomcat, JBoss EAP - Hyperscale PaaS for Any Java App by Haixia Cheng and Edward Burns will demo how to deploy any Java appson Azure App Service. Buildpacks: Paketo Buildpacks: The Best Way to Build Java Container Images? by Anthony Dahanne and David O'Sullivan will explore the benefits of buildpacks for Java containerization, comparing them with traditional Dockerfile-based approaches. Europe, Middle East and Africa - April 10, 9:00am – 12:30pm GMT Java 25: Explore The Hidden Gems of Java 25 with Mohamed Taman as he uncovers key Java SE features, updates, and fixes that will simplify migration to new Java and enhance your daily development workflow. GitHub Copilot: Use GitHub Copilot in your favorite Java IDEs by Julia Kordick and Brian Benz will show how to maximize productivity with GitHub Copilot’s latest features in IntelliJ, VS Code, and Eclipse. LangChain4j: AI-Powered Development: Hands-On Techniques for Immediate Impact by Lize Raes will explore AI tools like Cursor, Devin, and GitHub Workspace to help developers accelerate workflows and embrace AI-driven coding practices. Data and AI: Powering Spring AI with RAG and NoSQL by Theo van Kraay will demo how integrating Cosmos DB as vector store with Spring AI enables scalable, intelligent and high performing apps. Spring Security: Passkeys, One-Time Tokens: Passwordless Spring Security by Daniel Garnier-Moiroux dives into latest passwordless authentication methods in Spring Security with real-world implementation demos. Virtual Threads: Virtual Threads in Action with Jakarta EE Core Profile by Daniel Kec explores Helidon 4, the first Jakarta EE Core Profile runtime built on a pure Virtual Thread-based web server. Web apps: Simplifying Web App Development with HTMX and Hypermedia by Frederik Hahne shows how HTMX and modern template engines simplify Java web development by reducing reliance on complex single-page apps. Register and attend to earn rewards 🚀 Join the JDConf Experience and Earn Microsoft Rewards! 🚀 The first 300 attendees to check-in live for one of the JDConf - America, Europe or Asia - will receive 5,000 Microsoft Rewards points. How to Participate: Attendance Rewards: For your check-in to be counted you will need to do one of the following on the day of the event: Go to the JDConf Event details page on the Reactor website, Sign in with your Microsoft account (top right corner) and then check-in on the right-hand side, or Click the Join live stream link in the confirmation or reminder e-mail you receive to the Microsoft account e-mail address you registered with, or Click the link in the calendar reminder email, you will see the option to add the event to your calendar in your Microsoft account confirmation email. Points Distribution: Microsoft Rewards points will be added to the participants' Microsoft accounts within 60 days following the event. To earn points, you must use an email that is associated with a Microsoft account. You will receive an e-mail from the Microsoft Reactor team if you are eligible and earn the Microsoft Rewards. Points can be used towards many different rewards, check out Microsoft rewards to see what rewards are available in your region. Terms | Privacy RSVP now - engage, learn, and code the future with AI! Do not miss out – RSVP now and be part of the future of Java at JDConf 2025! We are calling all Java enthusiasts and developers around the globe to join us for a two-day event on April 9 and 10. This is more than just a conference. It is a chance to engage with the community, learn from the experts, and help drive Java technology forward. Get ready to dive into deep Java insights, connect with fellow developers, and discover the latest innovations that are shaping the world of Java. Let us gather to celebrate our passion for Java, share knowledge, and explore new possibilities together. Make sure you are there to push the boundaries of what Java can do. RSVP now at JDConf.com and let's make JDConf 2025 a milestone event for Java and its community. See you there! ⭐ RSVP now at JDConf.com 🌟170Views0likes0CommentsHow to set up subdirectory Multisite in WordPress on Azure App Service
WordPress Multisite is a feature of WordPress that enables you to run and manage multiple WordPress websites using the same WordPress installation. Follow these steps to setup Multisite in your WordPress website on App Service...9.6KViews1like13CommentsHow to set up a new WordPress website on Azure App Service
WordPress on Azure App Service combines the power of WordPress and Azure App Service to bring you a fully managed, scalable, and performant WordPress hosting solution. Let us learn how to create a new WordPress website on Azure App Service.19KViews2likes6CommentsLeveraging Azure Container Apps Labels for Environment-based Routing and Feature Testing
Azure Container Apps offers a powerful feature through labels and traffic splitting that can help developers easily manage multiple versions of an app, route traffic based on different environments, and enable controlled feature testing without disrupting live users. In this blog, we'll walk through a practical scenario where we deploy an experimental feature in a staging revision, test it with internal developers, and then switch the feature to production once it’s validated. We'll use Azure Container Apps labels and traffic splitting to achieve this seamless deployment process.445Views5likes1CommentIntroducing Serverless GPUs on Azure Container Apps
We're excited to announce the public preview of Azure Container Apps Serverless GPUs accelerated by NVIDIA. This feature provides customers with NVIDIA A100 GPUs and NVIDIA T4 GPUs in a serverless environment, enabling effortless scaling and flexibility for real-time custom model inferencing and other machine learning tasks. Serverless GPUs accelerate the speed of your AI development team by allowing you to focus on your core AI code and less on managing infrastructure when using NVIDIA accelerated computing. They provide an excellent middle layer option between Azure AI Model Catalog's serverless APIs and hosting models on managed compute. It provides full data governance as your data never leaves the boundaries of your container while still providing a managed, serverless platform from which to build your applications. Serverless GPUs are designed to meet the growing demands of modern applications by providing powerful NVIDIA accelerated computing resources without the need for dedicated infrastructure management. "Azure Container Apps' serverless GPU offering is a leap forward for AI workloads. Serverless NVIDIA GPUs are well suited for a wide array of AI workloads from real-time inferencing scenarios with custom models to fine-tuning. NVIDIA is also working with Microsoft to bring NVIDIA NIM microservices to Azure Container Apps to optimize AI inference performance.” - Dave Salvator, Director, Accelerated Computing Products, NVIDIA Key benefits of serverless GPUs Scale-to zero GPUs: Support for serverless scaling of NVIDIA A100 and T4 GPUs. Per-second billing: Pay only for the GPU compute you use. Built-in data governance: Your data never leaves the container boundary. Flexible compute options: Choose between NVIDIA A100 and T4 GPUs. Middle-layer for AI development: Bring your own model on a managed, serverless compute platform. Scenarios Whether you choose to use NVIDIA A100 or T4 GPUs will depend on the types of apps you're creating. The following are a couple example scenarios. For each scenario with serverless GPUs, you pay only for the compute you use with per-second billing, and your apps will automatically scale in and out from zero to meet the demand. NVIDIA T4 Real-time and batch inferencing: Using custom open-source models with fast startup times, automatic scaling, and a per-second billing model, serverless GPUs are ideal for dynamic applications that don't already have a serverless API in the model catalog. NVIDIA A100 Compute intensive machine learning scenarios: Significantly speed up applications that implement fine-tuned custom generative AI models, deep learning, or neural networks. High performance computing (HPC) and data analytics: Applications that require complex calculations or simulations, such as scientific computing and financial modeling as well as accelerated data processing and analysis among massive datasets. Get started with serverless GPUs Serverless GPUs are now available for workload profile environments in West US 3, Australia East, and Sweden Central regions with more regions to come. You will need to have quota enabled on your subscription in order to use serverless GPUs. By default, all Microsoft Enterprise Agreement customers will have one quota. If additional quota is needed, please request it here. Note: In order to achieve the best performance with serverless GPUs, use an Azure Container Registry (ACR) with artifact streaming enabled for your image tag. Follow steps here to enable artifact streaming on your ACR. From the portal, you can select to enable GPUs for your Consumption app in the container tab when creating your Container App or your Container App Job. You can also add a new consumption GPU workload profile to your existing Container App environment through the workload profiles UX in portal or through the CLI commands for managing workload profiles. Deploy a sample Stable Diffusion app To try out serverless GPUs, you can use the stable diffusion image which is provided as a quickstart during the container app create experience: In the container tab select the Use quickstart image box. In the quickstart image dropdown, select GPU hello world container. If you wish to pull the GPU container image into your own ACR to enable artifact streaming for improved performance, or if you wish to manually enter the image, you can find the image at mcr.microsoft.com/k8se/gpu-quickstart:latest. For full steps on using your own image with serverless GPUs, see the tutorial on using serverless GPUs in Azure Container Apps. Learn more about serverless GPUs With serverless GPUs, Azure Container Apps now simplifies the development of your AI applications by providing scale-to-zero compute, pay-as you go pricing, reduced infrastructure management, and more. To learn more, visit: Using serverless GPUs in Azure Container Apps (preview) | Microsoft Learn Tutorial: Generate images using serverless GPUs in Azure Container Apps (preview) | Microsoft Learn3.7KViews1like0CommentsConnection 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 Center502Views1like0CommentsConnection Between Web App and O365 Resources: Using Mail as an Example
TOC Introduction User Management Grant Permission Setup Security Mail Group Test References Introduction When using the Graph API to manage mail-related services, setting the permission to Delegate permission restricts the authorization to the user’s identity, limiting management to the specific user’s mailbox. While this might not be sufficient for certain business scenarios, Application permission, on the other hand, allows authorization under the App’s identity, enabling access to all users’ mailboxes within the tenant, which could be overly broad for certain use cases. Therefore, a method is required that allows the management of a specific mailbox using the App’s identity. This scenario is not recommended to use Delegate permission and requires some prerequisites, which are outlined in this article: Connection Between Web App and O365 Resources: Using SharePoint as an Example. User Management In your Microsoft Entra ID tenant, you will need: An admin user with permissions to "create users" and "assign roles." This user will perform the following operations. For simplicity, we’ll refer to this user as the admin user. An Exchange Administrator user who has the Exchange Administrator role. If not assigned, ensure to assign it to a user. In this example, the user is cch. A user account (or multiple users) to be managed by the Web App for mailbox operations. In this example, the user is support. Additionally, remember to visit https://admin.microsoft.com/ to assign a Microsoft 365 license to the new user, enabling mailbox access. Grant Permission For this example, we’ll use Managed Identity to grant the Mail.ReadWrite permission to the Enterprise Application corresponding to the Web App's Managed Identity. Note: Depending on your business requirements: You can replace the Managed Identity with a Multi-Tenant App Registration. You can also adjust Mail.ReadWrite to other permissions aligned with your business needs. Log in to the Azure Portal with your admin user and open a PowerShell CloudShell session. Modify and run the following commands to grant the necessary Graph API permissions to the Web App’s Managed Identity. Connect-MgGraph -Scopes "AppRoleAssignment.ReadWrite.All" $PrincipalId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" # Please setup your Managed Identity's OBJ ID $ResourceId = (Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" | Select-Object -ExpandProperty Id) $AppRoles = Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" -Property AppRoles | Select -ExpandProperty AppRoles | Where-Object { $_.Value -like "Mail.ReadWrite" } # Please setup your permission $AppRoles | ForEach-Object { $params = @{ "PrincipalId" = $PrincipalId "ResourceId" = $ResourceId "AppRoleId" = $_.Id } New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $PrincipalId -BodyParameter $params } Setup Security Mail Group Log in to the Azure Portal with an Exchange Administrator user, open a PowerShell CloudShell session, and run the following commands: Create a Security Mail Group. Add the mailboxes (e.g., support) that need to be accessible via the Web App to the group. Associate the Managed Identity's authorization with the Security Mail Group. az login --tenant XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX--use-device-code # Please setup your tenant id Connect-ExchangeOnline Connect-AzureAD New-DistributionGroup -Name "Policy Scope Group" -Alias "policy-scope-group" -Type Security Add-DistributionGroupMember -Identity "Policy Scope Group" -Member "XXX@XXX.com" # Please setup your receiver mailbox $AppId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" # Please setup your Managed Identity's APP ID $GroupId = (Get-AzureADGroup -SearchString "Policy Scope Group" | Select-Object ObjectId).ObjectId New-ApplicationAccessPolicy -AppId $AppId -PolicyScopeGroupId $GroupId -AccessRight RestrictAccess Important Notes Allow at least one hour for all configurations to take effect. Ensure the Microsoft 365 license has been assigned to the relevant user(s). Test You can deploy the following example code to your Web App. Replace support@xx.com with the mailbox to be accessed programmatically, and prepare another mailbox (e.g., cch@xx.com) for testing to ensure that only mailboxes within the Security Mail Group can be accessed. import requests from azure.identity import ManagedIdentityCredential def get_access_token(): credential = ManagedIdentityCredential() token = credential.get_token("https://graph.microsoft.com/.default") return token.token def get_latest_email_subject(target_email): access_token = get_access_token() headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } url = f"https://graph.microsoft.com/v1.0/users/{target_email}/mailFolders/Inbox/messages?$count=true" response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() if "value" in data and len(data["value"]) > 0: return data["value"][0].get("subject", "No Subject") else: print("No emails found in the inbox.") return None else: print("Failed to fetch emails.") print("Status Code:", response.status_code) print("Response:", response.json()) return None if __name__ == "__main__": print("=============================================") print("Fetching support@xx.com's latest email subject...") target_email = "support@xx.com" subject = get_latest_email_subject(target_email) if subject: print("Latest Email Subject:", subject) else: print("No email subject found.") print("=============================================") print("Fetching cch@xx.com's latest email subject...") target_email = "cch@xx.com" subject = get_latest_email_subject(target_email) if subject: print("Latest Email Subject:", subject) else: print("No email subject found.") After testing, you should observe that only the mailboxes of members within the Security Mail Group can be accessed by the Web App, while other mailboxes remain inaccessible. This ensures secure and specific access control. References Connection Between Web App and O365 Resources: Using SharePoint as an Example | Microsoft Community Hub Microsoft Graph permissions reference - Microsoft Graph | Microsoft Learn Connection Between Web App and O365 Resources: Using SharePoint as an Example | Microsoft Community Hub1.9KViews0likes0Comments