Quickstart: Deploy RESTful API application to Azure Spring Apps
Raksts
Piezīme
The Basic, Standard, and Enterprise plans will be deprecated starting from mid-March, 2025, with a 3 year retirement period. We recommend transitioning to Azure Container Apps. For more information, see the Azure Spring Apps retirement announcement.
This article describes how to deploy a RESTful API application protected by Microsoft Entra ID to Azure Spring Apps. The sample project is a simplified version based on the Simple Todo web application, which only provides the backend service and uses Microsoft Entra ID to protect the RESTful APIs.
These RESTful APIs are protected by applying role-based access control (RBAC). Anonymous users can't access any data and aren't allowed to control access for different users. Anonymous users only have the following three permissions:
Read: With this permission, a user can read the ToDo data.
Write: With this permission, a user can add or update the ToDo data.
Delete: With this permission, a user can delete the ToDo data.
After the deployment is successful, you can view and test the APIs through the Swagger UI.
The following diagram shows the architecture of the system:
This article describes the following options for creating resources and deploying them to Azure Spring Apps:
The Azure portal + Maven plugin option provides a more conventional way to create resources and deploy applications step by step. This option is suitable for Spring developers using Azure cloud services for the first time.
The Azure Developer CLI option is a more efficient way to automatically create resources and deploy applications through simple commands. The Azure Developer CLI uses a template to provision the Azure resources needed and to deploy the application code. This option is suitable for Spring developers who are familiar with Azure cloud services.
This article describes the following options for creating resources and deploying them to Azure Spring Apps:
The Azure portal + Maven plugin option provides a more conventional way to create resources and deploy applications step by step. This option is suitable for Spring developers using Azure cloud services for the first time.
The Azure CLI option uses a powerful command line tool to manage Azure resources. This option is suitable for Spring developers who are familiar with Azure cloud services.
An Azure subscription. If you don't have an Azure subscription, create an Azure free account before you begin.
One of the following roles:
Global Administrator or Privileged Role Administrator, for granting consent for apps requesting any permission, for any API.
Cloud Application Administrator or Application Administrator, for granting consent for apps requesting any permission for any API, except Microsoft Graph app roles (application permissions).
An Azure subscription, If you don't have an Azure subscription, create an Azure free account before you begin.
One of the following roles:
Global Administrator or Privileged Role Administrator, for granting consent for apps requesting any permission, for any API.
Cloud Application Administrator or Application Administrator, for granting consent for apps requesting any permission for any API, except Microsoft Graph app roles (application permissions).
An Azure subscription, If you don't have an Azure subscription, create an Azure free account before you begin.
One of the following roles:
Global Administrator or Privileged Role Administrator, for granting consent for apps requesting any permission, for any API.
Cloud Application Administrator or Application Administrator, for granting consent for apps requesting any permission for any API, except Microsoft Graph app roles (application permissions).
An Azure subscription, If you don't have an Azure subscription, create an Azure free account before you begin.
One of the following roles:
Global Administrator or Privileged Role Administrator, for granting consent for apps requesting any permission, for any API.
Cloud Application Administrator or Application Administrator, for granting consent for apps requesting any permission for any API, except Microsoft Graph app roles (application permissions).
cd ASA-Samples-Restful-Application
./mvnw spring-boot:run
3. Prepare the cloud environment
The main resources required to run this sample app are an Azure Spring Apps instance and an Azure Database for PostgreSQL instance. The following sections describe how to create these resources.
Go to the Azure portal and enter your credentials to sign in to the portal. The default view is your service dashboard.
3.2. Create an Azure Spring Apps instance
Use the following steps to create an Azure Spring Apps service instance:
Select Create a resource in the corner of the Azure portal.
Select Compute > Azure Spring Apps.
Fill out the Basics form with the following information:
Setting
Suggested value
Description
Subscription
Your subscription name.
The Azure subscription that you want to use for your server. If you have multiple subscriptions, choose the subscription in which you'd like to be billed for the resource.
Resource group
myresourcegroup
A new resource group name or an existing one from your subscription.
Name
myasa
A unique name that identifies your Azure Spring Apps service. The name must be between 4 and 32 characters long and can contain only lowercase letters, numbers, and hyphens. The first character of the service name must be a letter and the last character must be either a letter or a number.
Plan
Enterprise
The pricing plan that determines the resource and cost associated with your instance.
Region
The region closest to your users.
The location that is closest to your users.
Zone Redundant
Unselected
The option to create your Azure Spring Apps service in an Azure availability zone. This feature isn't currently supported in all regions.
Software IP plan
Pay-as-You-Go
The pricing plan that lets you pay as you go with Azure Spring Apps.
Terms
Selected
The agreement checkbox associated with Marketplace offering. You're required to select this checkbox.
Deploy sample project
Unselected
The option to use the built-in sample application.
Select Review and Create to review your selections. Then, select Create to provision the Azure Spring Apps instance.
On the toolbar, select the Notifications icon (a bell) to monitor the deployment process. After the deployment finishes, you can select Pin to dashboard, which creates a tile for this service on your Azure portal dashboard as a shortcut to the service's Overview page.
Select Go to resource to go to the Azure Spring Apps Overview page.
3.3. Prepare the PostgreSQL instance
Use the following steps to create an Azure Database for PostgreSQL server:
Go to the Azure portal and select Create a resource.
Select Databases > Azure Database for PostgreSQL.
Select the Flexible server deployment option.
Fill out the Basics tab with the following information:
Server name: my-demo-pgsql
Region: East US
PostgreSQL version: 14
Workload type: Development
Enable high availability: unselected
Authentication method: PostgreSQL authentication only
Admin username: myadmin
Password and Confirm password: Enter a password.
Use the following information to configure the Networking tab:
Connectivity method: Public access (allowed IP addresses)
Allow public access from any Azure service within Azure to this server: selected
Select Review + create to review your selections, and select Create to provision the server. This operation might take a few minutes.
Go to your PostgreSQL server in the Azure portal. On the Overview page, look for the Server name value, and then record it for later use. You need it to configure the environment variables for the app in Azure Spring Apps.
Select Databases from the navigation menu to create a database - for example, todo.
3.4. Connect app instance to PostgreSQL instance
Use the following steps to connect your service instances:
Go to your Azure Spring Apps instance in the Azure portal.
From the navigation menu, open Apps, and then select Create App.
On the Create App page, fill in the app name simple-todo-api, and then select Java artifacts as the deployment type.
Select Create to finish the app creation and then select the app to view the details.
Go to the app you created in the Azure portal. On the Overview page, select Assign endpoint to expose the public endpoint for the app. Save the URL for accessing the app after deployment.
Select Service Connector from the navigation pane, then select Create to create a new service connection.
Fill out the Basics tab with the following information:
Service type: DB for PostgreSQL flexible server
Connection name: An automatically generated name is populated, which can also be modified.
Subscription: Select your subscription.
PostgreSQL flexible server: my-demo-pgsql
PostgreSQL database: Select the database you created.
Client type: SpringBoot
Configure the Next: Authentication tab with the following information:
Piezīme
Microsoft recommends using the most secure authentication flow available. The authentication flow described in this procedure, such as for databases, caches, messaging, or AI services, requires a very high degree of trust in the application and carries risks not present in other flows. Use this flow only when more secure options, like managed identities for passwordless or keyless connections, are not viable. For local machine operations, prefer user identities for passwordless or keyless connections.
Select the authentication type you'd like to use between your compute service and target service.: Select Connection string.
Continue with...: Select Database credentials
Username: myadmin
Password: Enter your password.
Select Next: Networking. Use the default option Configure firewall rules to enable access to target service.
Select Next: Review and Create to review your selections, then select Create to create the connection.
3.5. Expose RESTful APIs
Use the following steps to expose your RESTful APIs in Microsoft Entra ID:
If you have access to multiple tenants, use the Directory + subscription filter (
) to select the tenant in which you want to register an application.
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
Enter a name for your application in the Name field - for example, Todo. Users of your app might see this name, and you can change it later.
For Supported account types, select Accounts in any organizational directory (Any Microsoft Entra directory - Multitenant) and personal Microsoft accounts.
Select Register to create the application.
On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to configure the YAML configuration file for this project.
Under Manage, select Expose an API, find the Application ID URI at the beginning of the page, and then select Add.
On the Edit application ID URI page, accept the proposed Application ID URI (api://{client ID}) or use a meaningful name instead of the client ID, such as api://simple-todo, and then select Save.
Under Manage, select Expose an API > Add a scope, and then enter the following information:
For Scope name, enter ToDo.Read.
For Who can consent, select Admins only.
For Admin consent display name, enter Read the ToDo data.
For Admin consent description, enter Allows authenticated users to read the ToDo data..
For State, keep it enabled.
Select Add scope.
Repeat the previous steps to add the other two scopes: ToDo.Write and ToDo.Delete.
3.6. Update the application configuration
Use the following steps to update the YAML file to use your Microsoft Entra registered application information to establish a relationship with the RESTful API application:
Locate src/main/resources/application.yml file for the simple-todo-api app. Update the configuration in the spring.cloud.azure.active-directory section to match the following example. Be sure to replace the placeholders with the values you created previously.
In v1.0 tokens, the configuration requires the client ID of the API, while in v2.0 tokens, you can use the client ID or the application ID URI in the request. You can configure both to properly complete the audience validation.
Use the following command to rebuild the sample project:
Bash
./mvnw clean package
3.1. Provide names for each resource
Create variables to hold the resource names by using the following commands. Be sure to replace the placeholders with your own values.
Piezīme
Microsoft recommends using the most secure authentication flow available. The authentication flow described in this procedure, such as for databases, caches, messaging, or AI services, requires a very high degree of trust in the application and carries risks not present in other flows. Use this flow only when more secure options, like managed identities for passwordless or keyless connections, are not viable. For local machine operations, prefer user identities for passwordless or keyless connections.
Use the following steps to create a new resource group:
Use the following command to sign in to the Azure CLI:
Azure CLI
az login
Use the following command to set the default location:
Azure CLI
az configure --defaultslocation=${LOCATION}
Use the following command to list all available subscriptions to determine the subscription ID to use:
Azure CLI
az account list --output table
Use the following command to set the default subscription:
Azure CLI
az account set --subscription<subscription-ID>
Use the following command to create a resource group:
Azure CLI
az group create --resource-group${RESOURCE_GROUP}
Use the following command to set the newly created resource group as the default resource group:
Azure CLI
az configure --defaultsgroup=${RESOURCE_GROUP}
3.3. Install extension and register namespace
Use the following commands to install the Azure Spring Apps extension for the Azure CLI and register the Microsoft.SaaS namespace:
Azure CLI
az extension add --name spring --upgradeaz provider register --namespace Microsoft.SaaS
3.4. Create an Azure Spring Apps instance
Use the following steps to create a service instance and an application in the instance:
Use the following command to accept the legal terms and privacy statements for the Enterprise plan:
Piezīme
This step is necessary only if your subscription has never been used to create an Enterprise plan instance of Azure Spring Apps.
Azure CLI
az term accept \
--publisher vmware-inc \
--product azure-spring-cloud-vmware-tanzu-2 \
--plan asa-ent-hr-mtr
Use the following command to create an Azure Spring Apps service instance:
Azure CLI
az spring create --name${AZURE_SPRING_APPS_NAME}--sku enterprise
Use the following command to create an application in the Azure Spring Apps instance:
Azure CLI
az spring app create \
--service${AZURE_SPRING_APPS_NAME} \
--name${APP_NAME} \
--assign-endpointtrue
3.5. Prepare the PostgreSQL instance
The Spring web app uses H2 for the database in localhost and Azure Database for PostgreSQL for the database in Azure.
Use the following command to create a PostgreSQL instance:
Piezīme
Microsoft recommends using the most secure authentication flow available. The authentication flow described in this procedure, such as for databases, caches, messaging, or AI services, requires a very high degree of trust in the application and carries risks not present in other flows. Use this flow only when more secure options, like managed identities for passwordless or keyless connections, are not viable. For local machine operations, prefer user identities for passwordless or keyless connections.
Specifying 0.0.0.0 enables public access from any resources deployed within Azure to access your server.
3.6. Connect app instance to PostgreSQL instance
After the application instance and the PostgreSQL instance are created, the application instance can't access the PostgreSQL instance directly. Use the following steps to enable the app to connect to the PostgreSQL instance:
Use the following command to get the PostgreSQL instance's fully qualified domain name:
Use the following command to provide the spring.datasource. properties to the app through environment variables:
Piezīme
Microsoft recommends using the most secure authentication flow available. The authentication flow described in this procedure, such as for databases, caches, messaging, or AI services, requires a very high degree of trust in the application and carries risks not present in other flows. Use this flow only when more secure options, like managed identities for passwordless or keyless connections, are not viable. For local machine operations, prefer user identities for passwordless or keyless connections.
Azure CLI
az spring app update \
--service${AZURE_SPRING_APPS_NAME} \
--name${APP_NAME} \
--env SPRING_DATASOURCE_URL="jdbc:postgresql://${PSQL_FQDN}:5432/${POSTGRESQL_DB}?sslmode=require" \
SPRING_DATASOURCE_USERNAME="${POSTGRESQL_ADMIN_USERNAME}" \
SPRING_DATASOURCE_PASSWORD="${POSTGRESQL_ADMIN_PASSWORD}"
3.7. Expose RESTful APIs
Use the following steps to expose the RESTful APIs:
Use the following command to create a Microsoft Entra ID application:
Azure CLI
az ad app create \
--display-name${TODO_APP_NAME} \
--sign-in-audience AzureADandPersonalMicrosoftAccount \
--identifier-uris${TODO_APP_URL}
Use the following command to create a service principal for the application:
Azure CLI
az ad sp create --id${TODO_APP_URL}
Use the following command to generate permission IDs:
api=$(echo '{
"oauth2PermissionScopes": [
{
"adminConsentDescription": "Allows authenticated users to delete the ToDo data",
"adminConsentDisplayName": "Delete the ToDo data",
"id": "'$permissionid1'",
"isEnabled": true,
"type": "Admin",
"userConsentDescription": null,
"userConsentDisplayName": null,
"value": "ToDo.Delete"
},
{
"adminConsentDescription": "Allows authenticated users to write the ToDo data",
"adminConsentDisplayName": "Write the ToDo data",
"id": "'$permissionid2'",
"isEnabled": true,
"type": "Admin",
"userConsentDescription": null,
"userConsentDisplayName": null,
"value": "ToDo.Write"
},
{
"adminConsentDescription": "Allows authenticated users to read the ToDo data",
"adminConsentDisplayName": "Read the ToDo data",
"id": "'$permissionid3'",
"isEnabled": true,
"type": "Admin",
"userConsentDescription": null,
"userConsentDisplayName": null,
"value": "ToDo.Read"
}
]}')
Use the following command to add scopes:
Azure CLI
az ad app update \
--id${TODO_APP_URL} \
--setapi="$api"
Use the following command to get the tenant ID to use in the next step:
Azure CLI
az account show --query"tenantId"--output tsv
Use the following command to get the application ID to use in the next steps:
Azure CLI
appid=$(az ad app show \
--id${TODO_APP_URL} \
--query appId \
--output tsv);
echo $appid
3.8. Update the application configuration
Use the following steps to update the YAML file to use your Microsoft Entra registered application information to establish a relationship with the RESTful API application:
Locate src/main/resources/application.yml file for the simple-todo-api app. Update the configuration in the spring.cloud.azure.active-directory section to match the following example. Be sure to replace the placeholders with the values you created previously.
In v1.0 tokens, the configuration requires the client ID of the API, while in v2.0 tokens, you can use the client ID or the application ID URI in the request. You can configure both to properly complete the audience validation.
The following list describes the command interactions:
OAuth2 login: You need to authorize the sign in to Azure based on the OAuth2 protocol.
Select subscription: Select the subscription list number of the Azure Spring Apps instance you created, which defaults to the first subscription in the list. If you use the default number, press Enter directly.
Use existing Azure Spring Apps in Azure: Press y to use the existing Azure Spring Apps instance.
Select Azure Spring Apps for deployment: Select the number of the Azure Spring Apps instance you created. If you use the default number, press Enter directly.
Use existing app in Azure Spring Apps <your-instance-name>: Press y to use the app created.
Confirm to save all the above configurations: Press y. If you press n, the configuration isn't saved in the POM files.
Use the following command to deploy the app:
Bash
./mvnw azure-spring-apps:deploy
The following list describes the command interaction:
OAuth2 login: You need to authorize the sign in to Azure based on the OAuth2 protocol.
After the command is executed, you can see from the following log messages that the deployment was successful:
Output
[INFO] Deployment Status: Running
[INFO] InstanceName:simple-todo-api-default-15-xxxxxxxxx-xxxxx Status:Running Reason:null DiscoverStatus:N/A
[INFO] Getting public url of app(simple-todo-api)...
[INFO] Application url: https://<your-Azure-Spring-Apps-instance-name>-simple-todo-api.azuremicroservices.io
Use the following command to deploy the app based on source code:
Azure CLI
az spring app deploy \
--service${AZURE_SPRING_APPS_NAME} \
--name${APP_NAME} \
--build-env BP_JVM_VERSION=17 \
--source-path .
You can now access the RESTful API to see if it works.
5.1. Request an access token
The RESTful APIs act as a resource server, which is protected by Microsoft Entra ID. Before acquiring an access token, you must register another application in Microsoft Entra ID and grant permissions to the client application, which is named ToDoWeb.
Register the client application
Use the following steps to register an application in Microsoft Entra ID, which is used to add the permissions for the ToDo app:
If you have access to multiple tenants, use the Directory + subscription filter (
) to select the tenant in which you want to register an application.
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
Enter a name for your application in the Name field - for example, ToDoWeb. Users of your app might see this name, and you can change it later.
For Supported account types, use the default value Accounts in this organizational directory only.
Select Register to create the application.
On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to acquire an access token.
Select API permissions > Add a permission > My APIs. Select the ToDo application that you registered earlier, and then select the ToDo.Read, ToDo.Write, and ToDo.Delete permissions. Select Add permissions.
Select Grant admin consent for <your-tenant-name> to grant admin consent for the permissions you added.
Add user to access the RESTful APIs
Use the following steps to create a member user in your Microsoft Entra tenant. Then, the user can manage the data of the ToDo application through RESTful APIs.
Under Manage, select Users > New user > Create new user.
On the Create new user page, enter the following information:
User principal name: Enter a name for the user.
Display name: Enter a display name for the user.
Password: Copy the autogenerated password provided in the Password box.
Piezīme
New users must complete the first sign-in authentication and update their passwords, otherwise, you receive an AADSTS50055: The password is expired error when you get the access token.
When a new user logs in, they receive an Action Required prompt. They can choose Ask later to skip the validation.
Select Review + create to review your selections. Select Create to create the user.
Update the OAuth2 configuration for Swagger UI authorization
Use the following steps to update the OAuth2 configuration for Swagger UI authorization. Then, you can authorize users to acquire access tokens through the ToDoWeb app.
Open your Microsoft Entra ID tenant in the Azure portal, and go to the registered ToDoWeb app.
Under Manage, select Authentication, select Add a platform, and then select Single-page application.
Use the format <your-app-exposed-application-URL-or-endpoint>/swagger-ui/oauth2-redirect.html as the OAuth2 redirect URL in the Redirect URIs field, and then select Configure.
You can now access the RESTful API to see if it works.
5.1. Request an access token
The RESTful APIs act as a resource server, which is protected by Microsoft Entra ID. Before acquiring an access token, you're required to register another application in Microsoft Entra ID and grant permissions to the client application, which is named ToDoWeb.
Register the client application
Use the following steps to register the client application:
Use the following command to create a Microsoft Entra ID application, which is used to add the permissions for the ToDo app:
Azure CLI
az ad app create \
--display-name${TODOWEB_APP_NAME} \
--sign-in-audience AzureADMyOrg \
--identifier-uris${TODOWEB_APP_URL}
Use the following command to add permissions:
Azure CLI
az ad app permission add \
--id api://simple-todowebtest2 \
--api$appid \
--api-permissions$permissionid1=Scope $permissionid2=Scope $permissionid3=Scope
Use the following command to grant admin consent for the permissions you added:
Azure CLI
az ad app permission admin-consent --id${TODOWEB_APP_URL}
Use the following command to get the client ID of the ToDoWeb app used in the Obtain the access token step:
Azure CLI
az ad app show \
--id${TODOWEB_APP_URL} \
--query appId \
--output tsv
Add user to access the RESTful APIs
Use the following command to create a member user in your Microsoft Entra tenant. Then, the user can manage the data of the ToDo application through RESTful APIs:
Piezīme
Microsoft recommends using the most secure authentication flow available. The authentication flow described in this procedure, such as for databases, caches, messaging, or AI services, requires a very high degree of trust in the application and carries risks not present in other flows. Use this flow only when more secure options, like managed identities for passwordless or keyless connections, are not viable. For local machine operations, prefer user identities for passwordless or keyless connections.
Azure CLI
az ad user create \
--display-name${NEW_MEMBER_USERNAME} \
--password${NEW_MEMBER_PASSWORD} \
--user-principal-name${USER_PRINCIPAL_NAME}
Update the OAuth2 configuration for Swagger UI authorization
Use the following steps to update the OAuth2 configuration:
Use the following command to get the object ID of the ToDoWeb app:
Azure CLI
az ad app show --id${TODOWEB_APP_URL}--query id
Use the following command to get the URL of your simple-todo-api app:
Azure CLI
az spring app show \
--name${APP_NAME} \
--service${AZURE_SPRING_APPS_NAME} \
--query properties.url
Use the following command to update the OAuth2 configuration for Swagger UI authorization, replacing the <object-id> and <URL> placeholders with the parameter values you got. Then, you can authorize users to acquire access tokens through the ToDoWeb app.
The following list describes the command interactions:
OAuth2 login: You need to authorize the sign in to Azure based on the OAuth2 protocol.
Please enter a new environment name: Provide an environment name. This name is used as a suffix for the resource group created to hold all the Azure resources. This name should be unique within your Azure subscription.
The console outputs messages similar to the following example:
Output
Initializing a new project (azd init)
Downloading template code to: <your-local-path>
(✓) Done: Initialized git repository
Enter a new environment name: <your-env-name>
SUCCESS: New project initialized!
You can view the template code in your directory: <your-local-path>
Learn more about running 3rd party code on our DevHub: https://aka.ms/azd-third-party-code-notice
3. Prepare the cloud environment
The main resources required to run this sample app are an Azure Spring Apps instance and an Azure Database for PostgreSQL instance. The following sections describe how to create these resources.
Go to the Azure portal and enter your credentials to sign in to the portal. The default view is your service dashboard.
3.2. Create an Azure Spring Apps instance
Use the following steps to create a service instance:
Select Create a resource in the corner of the portal.
Select Compute > Azure Spring Apps.
Fill out the Basics form. Use the following table as a guide for completing the form. The recommended Plan value is Standard consumption & dedicated (preview).
Setting
Suggested value
Description
Subscription
Your subscription name.
The Azure subscription that you want to use for your server. If you have multiple subscriptions, choose the subscription in which you'd like to be billed for the resource.
Resource group
myresourcegroup
A new resource group name or an existing one from your subscription.
Name
myasa
A unique name that identifies your Azure Spring Apps service. The name must be between 4 and 32 characters long and can contain only lowercase letters, numbers, and hyphens. The first character of the service name must be a letter and the last character must be either a letter or a number.
Plan
Standard consumption & dedicated (preview)
The pricing plan determines the resources and cost associated with your instance.
Region
The region closest to your users.
The location that's closest to your users.
Container Apps Environment
myenvironment
The option to select which Container Apps environment instance to share the same virtual network with other services and resources.
Use the following table as a guide for the Container Apps Environment creation:
Setting
Suggested value
Description
Environment name
myenvironment
A unique name that identifies your Azure Container Apps Environment service.
Plan
Consumption
The pricing plan determines the resources and cost associated with your instance.
Zone Redundant
Disabled
The option to create your Container Apps Environment service in an Azure availability zone.
Select Review and Create to review your selections. Then, select Create to provision the Azure Spring Apps instance.
On the toolbar, select the Notifications icon (a bell) to monitor the deployment process. After the deployment finishes, you can select Pin to dashboard, which creates a tile for this service on your Azure portal dashboard as a shortcut to the service's Overview page.
Select Go to resource to open the service's Overview page.
Svarīgi
The Consumption workload profile has a pay-as-you-go billing model, with no starting cost. You're billed for the dedicated workload profile based on the provisioned resources. For more information, see Workload profiles in Azure Container Apps and Azure Spring Apps pricing.
3.3. Prepare the PostgreSQL instance
Use the following steps to create an Azure Database for PostgreSQL server:
Go to the Azure portal and select Create a resource.
Select Databases > Azure Database for PostgreSQL.
Select the Flexible server deployment option.
Fill out the Basics tab with the following information:
Server name: my-demo-pgsql
Region: East US
PostgreSQL version: 14
Workload type: Development
Enable high availability: unselected
Authentication method: PostgreSQL authentication only
Admin username: myadmin
Password and Confirm password: Enter a password.
Use the following information to configure the Networking tab:
Connectivity method: Public access (allowed IP addresses)
Allow public access from any Azure service within Azure to this server: selected
Select Review + create to review your selections, and select Create to provision the server. This operation might take a few minutes.
Go to your PostgreSQL server in the Azure portal. On the Overview page, look for the Server name value, and then record it for later use. You need it to configure the environment variables for the app in Azure Spring Apps.
Select Databases from the navigation menu to create a database - for example, todo.
3.4. Connect app instance to PostgreSQL instance
Use the following steps to connect your service instances:
Go to your Azure Spring Apps instance in the Azure portal.
From the navigation menu, open Apps, and then select Create App.
On the Create App page, fill in the app name simple-todo-api and select Java artifacts as the deployment type.
Select Create to finish the app creation and select the app to view the details.
Go to the app you created in the Azure portal. On the Overview page, select Assign endpoint to expose the public endpoint for the app. Save the URL for accessing the app after deployment.
Go to the app you created, expand Settings and select Configuration from the navigation menu, and then select Environment variables to set the environment variables.
Add the following environment variables for the PostgreSQL connection, and then select Save to finish the app configuration update. Be sure to replace the placeholders with your own values that you created previously.
If you have access to multiple tenants, use the Directory + subscription filter (
) to select the tenant in which you want to register an application.
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
Enter a name for your application in the Name field - for example, Todo. Users of your app might see this name, and you can change it later.
For Supported account types, select Accounts in any organizational directory (Any Microsoft Entra directory - Multitenant) and personal Microsoft accounts.
Select Register to create the application.
On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to configure the YAML configuration file for this project.
Under Manage, select Expose an API, find the Application ID URI at the beginning of the page, and then select Add.
On the Edit application ID URI page, accept the proposed Application ID URI (api://{client ID}) or use a meaningful name instead of the client ID, such as api://simple-todo, and then select Save.
Under Manage, select Expose an API > Add a scope, and then enter the following information:
For Scope name, enter ToDo.Read.
For Who can consent, select Admins only.
For Admin consent display name, enter Read the ToDo data.
For Admin consent description, enter Allows authenticated users to read the ToDo data..
For State, keep it enabled.
Select Add scope.
Repeat the previous steps to add the other two scopes: ToDo.Write and ToDo.Delete.
3.6. Update the application configuration
Use the following steps to update the YAML file to use your Microsoft Entra registered application information to establish a relationship with the RESTful API application:
Locate src/main/resources/application.yml file for the simple-todo-api app. Update the configuration in the spring.cloud.azure.active-directory section to match the following example. Be sure to replace the placeholders with the values you created previously.
In v1.0 tokens, the configuration requires the client ID of the API, while in v2.0 tokens, you can use the client ID or the application ID URI in the request. You can configure both to properly complete the audience validation.
Use the following command to rebuild the sample project:
Bash
./mvnw clean package
3.1. Prepare the Azure resources
Use the following steps to provision the required Azure resources:
Run the following command to log in to Azure with OAuth2. Ignore this step if you already logged in.
Bash
azd auth login
Run the following command to enable the Azure Spring Apps feature:
Bash
azd config set alpha.springapp on
Run the following command to package a deployable copy of your application, provision the template's infrastructure to Azure, and deploy the application code to those newly provisioned resources:
Bash
azd provision
The following list describes the command interactions:
Select an Azure Subscription to use: Use arrows to move, type to filter, then press Enter.
Select an Azure location to use: Use arrows to move, type to filter, then press Enter.
The console outputs messages similar to the following example:
Output
SUCCESS: Your application was provisioned in Azure in xx minutes xx seconds.
You can view the resources created under the resource group rg-<your-environment-name>> in Azure Portal:
https://portal.azure.com/#@/resource/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>/overview
Piezīme
This command might take a while to complete. You see a progress indicator as it provisions Azure resources.
3.2. Expose RESTful APIs
Use the following steps to expose your RESTful APIs in Microsoft Entra ID:
If you have access to multiple tenants, use the Directory + subscription filter (
) to select the tenant in which you want to register an application.
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
Enter a name for your application in the Name field - for example, Todo. Users of your app might see this name, and you can change it later.
For Supported account types, select Accounts in any organizational directory (Any Microsoft Entra directory - Multitenant) and personal Microsoft accounts.
Select Register to create the application.
On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to configure the YAML configuration file for this project.
Under Manage, select Expose an API, find the Application ID URI at the beginning of the page, and then select Add.
On the Edit application ID URI page, accept the proposed Application ID URI (api://{client ID}) or use a meaningful name instead of the client ID, such as api://simple-todo, and then select Save.
Under Manage, select Expose an API > Add a scope, and then enter the following information:
For Scope name, enter ToDo.Read.
For Who can consent, select Admins only.
For Admin consent display name, enter Read the ToDo data.
For Admin consent description, enter Allows authenticated users to read the ToDo data..
For State, keep it enabled.
Select Add scope.
Repeat the previous steps to add the other two scopes: ToDo.Write and ToDo.Delete.
3.3. Update the application configuration
Use the following steps to update the YAML file to use your Microsoft Entra registered application information to establish a relationship with the RESTful API application:
Locate src/main/resources/application.yml file for the simple-todo-api app. Update the configuration in the spring.cloud.azure.active-directory section to match the following example. Be sure to replace the placeholders with the values you created previously.
In v1.0 tokens, the configuration requires the client ID of the API, while in v2.0 tokens, you can use the client ID or the application ID URI in the request. You can configure both to properly complete the audience validation.
The following list describes the command interactions:
OAuth2 login: You need to authorize the sign in to Azure based on the OAuth2 protocol.
Select subscription: Select the subscription list number of the Azure Spring Apps instance you created, which defaults to the first subscription in the list. If you use the default number, press Enter directly.
Use existing Azure Spring Apps in Azure: Press y to use the existing Azure Spring Apps instance.
Select Azure Spring Apps for deployment: Select the number of the Azure Spring Apps instance you created. If you use the default number, press Enter directly.
Use existing app in Azure Spring Apps <your-instance-name>: Press y to use the app created.
Confirm to save all the above configurations: Press y. If you press n, the configuration isn't saved in the POM files.
Use the following command to deploy the app:
Bash
./mvnw azure-spring-apps:deploy
The following list describes the command interaction:
OAuth2 login: You need to authorize the sign in to Azure based on the OAuth2 protocol.
After the command is executed, you can see from the following log messages that the deployment was successful:
Output
[INFO] Deployment(default) is successfully created
[INFO] Starting Spring App after deploying artifacts...
[INFO] Deployment Status: Running
[INFO] InstanceName:demo--default-xxxxxxx-xxxxxxxxx-xxxxx Status:Running Reason:null DiscoverStatus:NONE
[INFO] Getting public url of app(demo)...
[INFO] Application url: https://demo.<unique-identifier>.<region-name>.azurecontainerapps.io
Use the following steps to package the app, provision the Azure resources required by the web application, and then deploy to Azure Spring Apps.
Run the following command to package a deployable copy of your application:
Bash
azd package
Run the following command to deploy the application code to those newly provisioned resources:
Bash
azd deploy
The console outputs messages similar to the following example:
Output
Deploying services (azd deploy)
WARNING: Feature 'springapp' is in alpha stage.
To learn more about alpha features and their support, visit https://aka.ms/azd-feature-stages.
...
Deploying service simple-todo-api (Fetching endpoints for spring app service)
- Endpoint: https://simple-todo-api.xxxxxxxx-xxxxxxxx.xxxxxx.azurecontainerapps.io
SUCCESS: Your application was deployed to Azure in xx minutes xx seconds.
You can view the resources created under the resource group rg-<your-environment-name> in Azure Portal:
https://portal.azure.com/#@/resource/subscriptions/<your-subscription-id>/resourceGroups/rg-<your-environment-name>/overview
The output Endpoint is the base endpoint to access the ToDo API application.
Piezīme
You can also use azd up to combine the previous three commands: azd provision (provisions Azure resources), azd package (packages a deployable copy of your application), and azd deploy (deploys application code). For more information, see Azure-Samples/ASA-Samples-Restful-Application.
5. Validate the app
You can now access the RESTful API to see if it works.
5.1. Request an access token
The RESTful APIs act as a resource server, which is protected by Microsoft Entra ID. Before acquiring an access token, you must register another application in Microsoft Entra ID and grant permissions to the client application, which is named ToDoWeb.
Register the client application
Use the following steps to register an application in Microsoft Entra ID, which is used to add the permissions for the ToDo app:
If you have access to multiple tenants, use the Directory + subscription filter (
) to select the tenant in which you want to register an application.
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
Enter a name for your application in the Name field - for example, ToDoWeb. Users of your app might see this name, and you can change it later.
For Supported account types, use the default value Accounts in this organizational directory only.
Select Register to create the application.
On the app Overview page, look for the Application (client) ID value, and then record it for later use. You need it to acquire an access token.
Select API permissions > Add a permission > My APIs. Select the ToDo application that you registered earlier, and then select the ToDo.Read, ToDo.Write, and ToDo.Delete permissions. Select Add permissions.
Select Grant admin consent for <your-tenant-name> to grant admin consent for the permissions you added.
Add user to access the RESTful APIs
Use the following steps to create a member user in your Microsoft Entra tenant. Then, the user can manage the data of the ToDo application through RESTful APIs.
Under Manage, select Users > New user > Create new user.
On the Create new user page, enter the following information:
User principal name: Enter a name for the user.
Display name: Enter a display name for the user.
Password: Copy the autogenerated password provided in the Password box.
Piezīme
New users must complete the first sign-in authentication and update their passwords, otherwise, you receive an AADSTS50055: The password is expired error when you get the access token.
When a new user logs in, they receive an Action Required prompt. They can choose Ask later to skip the validation.
Select Review + create to review your selections. Select Create to create the user.
Update the OAuth2 configuration for Swagger UI authorization
Use the following steps to update the OAuth2 configuration for Swagger UI authorization. Then, you can authorize users to acquire access tokens through the ToDoWeb app.
Open your Microsoft Entra ID tenant in the Azure portal, and go to the registered ToDoWeb app.
Under Manage, select Authentication, select Add a platform, and then select Single-page application.
Use the format <your-app-exposed-application-URL-or-endpoint>/swagger-ui/oauth2-redirect.html as the OAuth2 redirect URL in the Redirect URIs field, and then select Configure.
Obtain the access token
Use the following steps to use OAuth 2.0 authorization code flow method to obtain an access token with Microsoft Entra ID, then access the RESTful APIs of the ToDo app:
Open the URL exposed by the app, then select Authorize to prepare the OAuth2 authentication.
In the Available authorizations window, enter the client ID of the ToDoWeb app in the client_id field, select all the scopes for Scopes field, ignore the client_secret field, and then select Authorize to redirect to the Microsoft Entra sign-in page.
After completing the sign in with the previous user, you're returned to the Available authorizations window.
5.2. Access the RESTful APIs
Use the following steps to access the RESTful APIs of the ToDo app in the Swagger UI:
Select the API POST /api/simple-todo/lists and then select Try it out. Enter the following request body, and then select Execute to create a ToDo list.
JSON
{
"name": "My List"
}
After the execution is complete, you see the following Response body:
JSON
{
"id": "<ID-of-the-ToDo-list>",
"name": "My List",
"description": null
}
Select the API POST /api/simple-todo/lists/{listId}/items and then select Try it out. For listId, enter the ToDo list ID you created previously, enter the following request body, and then select Execute to create a ToDo item.
JSON
{
"name": "My first ToDo item",
"listId": "<ID-of-the-ToDo-list>",
"state": "todo"
}
This action returns the following ToDo item:
JSON
{
"id": "<ID-of-the-ToDo-item>",
"listId": "<ID-of-the-ToDo-list>",
"name": "My first ToDo item",
"description": null,
"state": "todo",
"dueDate": "2023-07-11T13:59:24.9033069+08:00",
"completedDate": null
}
Select the API GET /api/simple-todo/lists and then select Execute to query ToDo lists. This action returns the following ToDo lists:
Select the API GET /api/simple-todo/lists/{listId}/items and then select Try it out. For listId, enter the ToDo list ID you created previously, and then select Execute to query the ToDo items. This action returns the following ToDo item:
JSON
[
{
"id": "<ID-of-the-ToDo-item>",
"listId": "<ID-of-the-ToDo-list>",
"name": "My first ToDo item",
"description": null,
"state": "todo",
"dueDate": "2023-07-11T13:59:24.903307+08:00",
"completedDate": null
}
]
Select the API PUT /api/simple-todo/lists/{listId}/items/{itemId} and then select Try it out. For listId, enter the ToDo list ID. For itemId, enter the ToDo item ID, enter the following request body, and then select Execute to update the ToDo item.
JSON
{
"id": "<ID-of-the-ToDo-item>",
"listId": "<ID-of-the-ToDo-list>",
"name": "My first ToDo item",
"description": "Updated description.",
"dueDate": "2023-07-11T13:59:24.903307+08:00",
"state": "inprogress"
}
This action returns the following updated ToDo item:
JSON
{
"id": "<ID-of-the-ToDo-item>",
"listId": "<ID-of-the-ToDo-list>",
"name": "My first ToDo item",
"description": "Updated description.",
"state": "inprogress",
"dueDate": "2023-07-11T05:59:24.903307Z",
"completedDate": null
}
Select the API DELETE /api/simple-todo/lists/{listId}/items/{itemId} and then select Try it out. For listId, enter the ToDo list ID. For itemId, enter the ToDo item ID, and then select Execute to delete the ToDo item. You should see that the server response code is 204.
6. Clean up resources
You can delete the Azure resource group, which includes all the resources in the resource group.
Use the following steps to delete the entire resource group, including the newly created service:
Locate your resource group in the Azure portal.
On the navigation menu, select Resource groups. Then, select the name of your resource group - for example, myresourcegroup.
On your resource group page, select Delete. Enter the name of your resource group in the text box to confirm deletion - for example, myresourcegroup. Then, select Delete.
Use the following command to delete the entire resource group, including the newly created service:
Use the following steps to delete the entire resource group, including the newly created service:
Locate your resource group in the Azure portal.
On the navigation menu, select Resource groups. Then, select the name of your resource group - for example, myresourcegroup.
On your resource group page, select Delete. Enter the name of your resource group in the text box to confirm deletion - for example, myresourcegroup. Then, select Delete.
Use the following command to delete all the Azure resources used in this sample application:
Bash
azd down
The following list describes the command interaction:
Total resources to delete: [your-resources-total], are you sure you want to continue?: Press y.
The console outputs messages similar to the following example:
Output
SUCCESS: Your application was removed from Azure in xx minutes xx seconds.
Pievienojieties meetup sērijai, lai kopā ar citiem izstrādātājiem un ekspertiem izveidotu mērogojamus AI risinājumus, kuru pamatā ir reālas lietošanas gadījumi.