Sunday, August 22, 2021

Azure service principal

An Azure Active Directory (Azure AD) service principal is the local representation of an application object in a single tenant or directory. ‎It functions as the identity of the application instance. Service principals define who can access the application, and what resources the application can access. A service principal is created in each tenant where the application is used and references the globally unique application object. The tenant secures the service principal’s sign in and access to resources.



A multi-tenant application is homed in a single-tenant (home tenant) and is designed to have instances in other tenants. Most software-as-a-service (SaaS) applications are designed for multi-tenancy. Use service principals to ensure the right security posture for the application and its users in both single-tenant and multi-tenant use cases.

Application registration

When you register your application with Azure AD, you're creating an identity configuration for your application that allows it to integrate with Azure AD. When you register an app in the Azure portal, you choose whether it's a single-tenant (only accessible in your tenant) or multi-tenant (accessible in other tenants) and can optionally set a redirect URI (where the access token is sent to).

When you've completed the app registration, you have a globally unique instance of the app (the application object) which lives within your home tenant or directory. You also have a globally unique ID for your app (the app or client ID).


If you register an application in the portal, an application object, as well as a service principal object, are automatically created in your home tenant.



Application object

An Azure AD application is defined by its one and only application object, which resides in the Azure AD tenant where the application was registered (known as the application's "home" tenant). An application object is used as a template or blueprint to create one or more service principal objects. A service principal is created in every tenant where the application is used.

The application object describes three aspects of an application.

1.       How the service can issue tokens in order to access the application.

2.       Resources that the application might need to access.

3.       The actions that the application can take.


Application Id

ApplicationId will be same for single application object that represents this application as well as it will be same for all service principals created for this application.

 

Object Id

ObjectId will be a unique value for application object and each of the service principal. This uniquely identifies the object in Azure AD.

Service principal object

To access resources that are secured by an Azure AD tenant, the entity that requires access must be represented by a security principal. This requirement is true for both users (user principal) and applications (service principal). The security principal defines the access policy and permissions for the user/application in the Azure AD tenant. This enables core features such as authentication of the user/application during sign-in, and authorization during resource access.

There are three types of service principal

1.       Application- The type of service principal is the local representation, or application instance, of a global application object in a single tenant or directory.

2.       Managed identity- This type of service principal is used to represent a managed identity. It is used for “linking” a Service Principal security object to an Azure Resource like a Virtual Machine, Web App, Logic App or similar. If you want to learn more about it, you can read my previous blog.

3.       Legacy- This type of service principal represents a legacy app, which is an app created before app registrations were introduced or an app created through legacy experiences.


Hope it will help you to understand service principle and in a future blog, we will use them

Keep sharing keep learning 

Wednesday, July 21, 2021

Authenticate Azure Functions with Swagger UI

 In this blog, we will see how we can secure our azure functions with API Keys and use swagger for API documentation. Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. If you want to learn more about azure function. Please look into my previous blog (link) about azure function to create rest serverless api .

There are multiple ways to secure your Azure Functions like API Keys, API Management, App Service Authentication (App registration in active directory), etc. If you want to make a start with minimal effort and less setup of Infrastructure, then API Keys is the ideal choice.

Azure Functions allows you to secure HTTP-triggered functions by API access key in the request. We can send HTTP request with help of Swagger, Postman, JavaScript etc.  As part of creating new Azure Functions, we can select the Authorization Level enum value.

Azure Functions with Swagger UI

I am creating new project in visual studio 2019 to demonstrate. How we can add swagger ui in azure function. We need follow below steps.

1.       Open visual studio 2019 and create new azure function project with name FunctionApp.Swagger


2.       Choose option as above screen. If you want to add swagger UI in API make sure you have selected Http Trigger with OpenAPI option.  

3.       In this project we are using Function level Authorization. When we set Authorization level then need to pass authentication token to access the resource. We will pass API key as authentication token with HTTP request       

4.       Once all information filled as above then we will click on create button. It will create Function1  as below

5.       If we run the azure function with help of Visual studio 2019. It will open console window with swagger ui url as above screen. In my case azure function swagger UI is http://localhost:7071/api/swagger/ui

6.       If we open the swagger ui url in browser it will display like this and we can make HTTP request

7.       When we run application in localhost, we don’t need to pass API key in Swagger UI. It will execute our HTTP request without it. Once we deploy the application in Azure then need to pass API key by clicking on Authorize


8.        You can see swagger UI added in our API and we can make HTTP request directly from browser with help of swagger

9.       Now we ready to deploy application Azure.

Consume Azure Function  

Once our application tested in local machine then we need to deploy it on Azure. I have created new azure function (djblogsfuncappwithswagger) in Azure with help of portal. Once azure function created in azure then we need to download the publish profile and publish our code directly from visual studio 2019.

Need to follow below steps to publish azure function in Azure

1.       Created new azure function (djblogsfuncappwithswagger) with consumption app service plan in portal

2.       Once azure function created then need to download publish profile to publish azure function code from visual studio 2019 as below

3.       Once azure function published in Azure then we can make HTTP request with help of swagger UI.

URL: https://djblogsfuncappwithswagger.azurewebsites.net/api/swagger/ui

4.       When we run API in browser without API Key it will give this Unauthorized error

401 Error: Unauthorized



 

5.       We can get API key from Azure function. Need to open azure portal and go to azure function there is default API key. This is created by default when azure function created.  If you want you can create multiple keys as per our requirement  


6.       We will copy the default key from functions keys and add that key in swagger authorize as below screen. 


7.       Once key added in Swagger UI Authorize and then we try to make HTTP request. It will be executed with HTTP code 200.  

8.       We can make the HTTP request from Postman as well by adding x-functions-key in HTTP request header like below screen shot.

9.       Same way we can make request from JavaScript and jQuery as well.

GitHub Link: https://github.com/deepakjoshiinfo/FunctionApp.Swagger/blob/master/WebApp/Pages/Index.cshtml

I have uploaded code in GitHub. You can download code from there

GitHub: https://github.com/deepakjoshiinfo/FunctionApp.Swagger

Hope it will help you give little idea about authorization and authentication of Azure functions

Keep sharing keep learning. Cheers

Wednesday, July 14, 2021

What is bicep in azure?

Bicep is a Domain Specific Language (DSL) for deploying Azure infrastructure (resources) declaratively. Bicep code is transpiled to standard ARM Template JSON files (Infrastructure as code file), which effectively treats the ARM Template as an Intermediate Language (IL). Bicep provides concise syntax, reliable type safety, and support for code reuse. We believe Bicep offers the best authoring experience for your Azure infrastructure as code solutions.

You can use Bicep instead of JSON to develop your Azure Resource Manager templates (ARM templates). The JSON syntax to create an ARM template can be verbose and require complicated expressions. Bicep syntax reduces that complexity and improves the development experience. Bicep is a transparent abstraction over ARM template JSON and doesn't lose any of the JSON template capabilities. During deployment, Bicep CLI transpiles a Bicep file into ARM template JSON.


Create Azure Resource (Infrastructure) in Visual studio code

We will create azure resource inside visual studio code with help of Bicep. Need to follow below steps.

1.       Install visual studio code below URL

https://code.visualstudio.com/download

2.       Once visual studio code is installed then need to add Bicep extension like below


3.       After installing Bicep then code IntelliSense will come in VS Code for azure resources. Now open to the folder from VS code file menu, where you want to create Bicep project and add new file name (main.bicep)   




4.       We will write code for azure storage account (infrastructure) inside bicep file like below. I have also mapped bicep code with azure storage account resource for better understanding.


Sample code:

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01'={
  name'bicepstoarge'
  location'eastus'
  kind:'Storage'
  sku:{
      name:'Premium_LRS'
  }
}

5.       Once code if written for azure resource (infrastructure) then build the code it will convert bicep file into ARM template JSON.

6.       To build the bicep file we need to run Bicep CLI in visual studio code terminal as below

Manual with PowerShell

https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/install#install-manually

 

# Create the install folder

$installPath = "$env:USERPROFILE\.bicep"

$installDir = New-Item -ItemType Directory -Path $installPath -Force

$installDir.Attributes += 'Hidden'

# Fetch the latest Bicep CLI binary

(New-Object Net.WebClient).DownloadFile("https://github.com/Azure/bicep/releases/latest/download/bicep-win-x64.exe", "$installPath\bicep.exe")

# Add bicep to your PATH

$currentPath = (Get-Item -path "HKCU:\Environment" ).GetValue('Path', '', 'DoNotExpandEnvironmentNames')

if (-not $currentPath.Contains("%USERPROFILE%\.bicep")) { setx PATH ($currentPath + ";%USERPROFILE%\.bicep") }

if (-not $env:path.Contains($installPath)) { $env:path += ";$installPath" }

# Verify you can now access the 'bicep' command.

bicep --help

# Done!

 


7.       Once Bicep CLI is installed, now build the bicep file below command

bicep build main.bicep    


8.       After build new JSON file (main.json) will created in visual studio code. It is ARM (Azure Resource Manager) template which we will deploy with help of Azure CLI.

9.       Once ARM templated (JSON) is created now we will deploy this resource in Azure with help of Azure CLI.

Deploy resources with ARM templates and Azure CLI

We will see how to use Azure CLI with Azure Resource Manager templates (ARM templates) to deploy your resources to Azure.

To deploy ARM template, install the latest version of the Azure CLI.

URL: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli

Deploy resource in Azure need to follow these steps

1.       Run az login to create a connection with Azure





 

2.       It will open azure portal login screen. We need to put our azure loginid and password.


3.       Once login done successfully then need to select the subscription, where you want to deploy your resource.

az account set --subscription "<Your Subscription name>"

 

4.       Once subscription is selected then we ready to deploy our ARM template (JSON) on azure. We will do that with below command

az deployment group create --resource-group DJBlogs --template-file main.json


5.       Once above command is executed successfully then resource will be created in Azure


Hope it will help you to give little idea about bicep and ARM template and We can use all these to put our application infrastructure in code repository and automate our infrastructure.

Keep sharing keep learning. Cheers

Saturday, June 5, 2021

Managed Identity

Managed Identity is an Azure feature, which allows Identity managed access to Azure resources. This improves security, by reducing the need for applications, to have credentials in code, configurations. It creates an identity, which is linked to an Azure resource. The identity can then be granted access to Azure resources.

A common challenge for developers is the management of secrets and credentials used to secure communication between different components making up a solution. Managed identities eliminate the need for developers to manage credentials. Managed identities provide an identity for applications to use when connecting to resources that support Azure Active Directory (Azure AD) authentication. Applications may use the managed identity to obtain Azure AD tokens. For example, an application may use a managed identity to access resources like Azure Key Vault where developers can store credentials in a secure manner or to access storage accounts.


In above diagram we are getting secret from key vault in Logic App with help of managed identity. I will explain all in detail.

We will do below things in this blog

1.       Create new secret inside key vault

2.       Create new Logic App and enable system assigned managed identity

3.       Add logic app inside key vault Access policies

4.       Make Http GET call from Logic App and get secret

Create new secret inside key vault

First, need to create new secret key inside key vault. In this example I am using my old key vault service djsecrets If you want to learn more about key vault. Please read my previous blog about key AzureKey Vault

Need follow below steps to add new secret key inside key vault

1.       Go to key vault 


2.       Create new secret key with “Name” with value “DJ Blogs

 


3.       Click on create then secret added in key vault. If we open the secret it will look like as below

Secret URL look like https://djsecrets.vault.azure.net/secrets/Name/version-number

If you want to get latest value every time, then we don’t need to add version number in URL then it will be  https://djsecrets.vault.azure.net/secrets/Name

This URL we will be used in our logic app to get the latest value of secret

Logic App and enable system assigned managed identity

Now we will create logic app which will get secret with help of HTTP Get request and managed identity authentication. If you want to learn more about logic app. Please read my previous blog Logic App.

Follow below steps to create logic app

1.       Go to your resource group where you want to create logic app and click on add button

 


2.       Creating logic app with name “djmanagedidentity” in Center US data center.

 

3.       Once Logic App created then enable system assigned managed identity in Logic App


4.       As above follow steps it will create Object ID now our resource ready for assign managed identity.

Add logic app inside key vault Access policies

Once in any resource system assigned managed identity enabled in azure then we can add that resource in Access policies of other resource to access it. Follow below steps to get key from key vault to logic app

1.       Go to your key vault and select access policies

 


2.       Click on Add Access Policy will add logic app object for access the secret


3.       Once logic app added in access policy. Now we will get the secret key value with help of HTTP GET request.

 

Http GET call from Logic App and get secret

Now managed identity setup between 2 resource (Key Vault and Logic App) within azure. To get secret in logic app need to add 2 steps inside logic app.

 


We need to add key vault secret URL and authentication details inside HTTP step like below

Method: GET

URL: https://djsecrets.vault.azure.net/secrets/Name?api-version=7.2

Audience: https://vault.azure.net

Once all this information filled as above now, we will run the logic app. It will show the input and output as below

Input

Output

 

Microsoft: What can a managed identity be used for?

Hope it will help you to understand managed identity in Azure and how you can use it.

Keep sharing keep learning 

Saturday, May 29, 2021

Migrating Window Authentication App into Azure

As you know Windows Authentication not supported in azure. When attempting to move legacy ASP.NET apps to Azure App Service, you might encounter a few challenges. However, Microsoft provide Azure App Service migration assistant which help you to migrate your on-premises application into Azure cloud. I have previously written blog about it. You can read more about in below link.

AppService Migration Assistant

We will walk through updating an ASP.NET application with Windows Integrated Authentication to use Azure Active Directory (AAD). It will help you to move your on-premises application into Azure PaaS (Web App). This post walks through some relatively minor tweaks that allow you to switch your site to use AAD for authentication and, if you want, AD group membership for authorization. These changes will enable deployment of those sites to Azure App Services.


To make the change we’re going to follow the below steps

1.       Ensure your site is setup to use SSL.

2.       Register your application in AAD.

3.       Get the necessary OWIN NuGet packages.

4.       Add in some startup code to use the OWIN authentication libraries.

 

Ensure your site is setup to use SSL

This demo I am using application which run with window authentication. First, we need ensure application use SSL (https) while running. You can enable by selecting project and set property SSL Enabled true


When you run application, it will run on port number 44362 as you can see in screenshot

URL: https://localhost: 44362/

Register your application in AAD

We need to register your application with your Azure Active Directory (AAD).

Need follow steps to register App with help of azure portal.

1.       Go to azure portal https://portal.azure.com

2.       Once your login in then go to Azure Active Directory


3.       Then need to click on App registration 


4.      After that click on New registration. It will open form as below


5.       Once all information filled as above then need to click on Register button

6.       Now our app is registered successfully in AAD and we can use created App client id and tenant id in our Web application.


 

Get the necessary OWIN NuGet packages.

OWIN (Open Web Interface for .NET) will significantly simplify the migration process. OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application.

The problem with System.Web is that it is way too bloated and coupled with IIS. You are forced to run it in IIS. The OWIN initiative is an attempt to modularize and decouple the Web Stack by adding abstraction.

OWIN is an open standard. http://owin.org/

Need to Install these OWIN (Open Web Interface for .NET) packages

1.       Microsoft.Owin.Host.SystemWeb

2.       Microsoft.Owin.Security.OpenIdConnect

3.       Microsoft.Owin.Security.Cookies


Microsoft.Owin.Host.SystemWeb

Middleware that enables OWIN-based applications to run on Internet Information Services (IIS) by using the ASP.NET request pipeline

 

Microsoft.Owin.Security.OpenIdConnect

Middleware that enables an application to use OpenIdConnect for authentication

 

Microsoft.Owin.Security.Cookies

Middleware that enables an application to maintain a user session by using cookies

  

Add in some startup code to use the OWIN authentication libraries

We need to add some code to the OWIN startup process and adjust the web.config.

Web.config


Once these 3 keys added in Web.config then need to create Startup.cs file inside App_Start Folder

Startup.cs


You can download code this code from GitHub

URL: https://github.com/deepakjoshiinfo/WindowsAuthToAzureAD 

Once we made changes in Startup.cs file then need to test the authencation working or not. I have just copied below code in About.aspx file

<div>

        <div>IsAuthenticated</div> <div><%= HttpContext.Current.User.Identity.IsAuthenticated %></div>

        <div>AuthenticationType</div> <div><%= HttpContext.Current.User.Identity.AuthenticationType %></div>

        <div>Name</div> <div><%= HttpContext.Current.User.Identity.Name %></div>

        <div>Is in "Group1"</div>

        <div><%= HttpContext.Current.User.IsInRole("Group1") %></div>

        <div>Is in "Group2"</div>

        <div><%= HttpContext.Current.User.IsInRole("Group2") %></div>

    </div>

When I run the application in my local machine it redirect me to Microsoft login page for Authentication 

Login with your domain UserId and Password then it will open our application


You can see user Authenticated from azure active directory. Now we can migrate this application in Azure Web App. If you want to learn more about web app read my previous post   Azure WebApps

Helpful links for more information

Convert ASP.NET Web Forms with Windows Authentication to use AAD

https://devblogs.microsoft.com/premier-developer/convert-asp-net-webforms-with-windows-authentication-to-use-aad/

QuickStart: Register an application with the Microsoft identity platform

https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Hope it will help you to migrate window authentication to azure active directory authentication.

Keep sharing keep learning. Cheers