Authenticate with Azure AD interactively and non-interactively (2023)

Protect a website with a Microsoft account

Securing your website or web API in Azure with a Microsoft account just got easier. By following these few steps, your website will be protected in minutes:

  • create one for freeblue account
  • Build and deploy your web site/apiAzure Portal
  • navigate to yourPosition->certifiedIn the Azure portal and enable App Service Authentication, selectSign in with a Microsoft account, save and go. Your new website is certified and secure.
Secure your site with Azure Ads

Now that your site is protected, you're happy, but then new requirements start to appear. For example. You want to enable your website to other users with minimal effort. You poke around the Azure portal, StackOverflow, and Google and discover that Azure Active Directory is the right choice. you followthese stepsand you have an Azure AD.

Authenticate with Azure AD interactively and non-interactively (1)

Before you can connect to the website using the credentials, the application must also be registered in Azure AD -> Application Registration.

Authenticate with Azure AD interactively and non-interactively (2)

All new users who will need to access the website/app must be granted access. This can be done from within the application itself using one of the methods listed below:

  1. Azure Active Directory->application registration-> select application ->set up->required permitslast clickPermission granted->Corporate application
  2. Azure Active Directory-> select application ->users and groups->Add user-> find the user and click on the option

My experience is that method #1 doesn't always work as expected, so I prefer to use the second method.

The app is now secure and new users can be added at any time. Choosing the free tierAzure AD, can add several users (MS calls it 500K objects).

If the application is closed typeASP.Net MVC, so you have successfully secured your website and lived happily ever after. But if it's not, and it's more like the new modern type, let's saymicroservice-ish, and use the web api to get some additional data, then the whole chain is not secure. For example. There is an app and a web API. The app can be MVC or any more modern SPA app, built with Vue or React or anything that pleases you and interacts with a web api to get data. Pretty much the de facto way of building apps today.

The current settings for app-only protection are shown below. The user interacts with the application, if this is the first time the user hits the application URL, the Azure AD protection mechanism will wake up and the user will be redirected to the Azure AD login page. The user provides the credentials and if all goes well, the user is redirected back to the app URI. The application in turn uses an API to retrieve data which in turn uses some kind of storage.

Authenticate with Azure AD interactively and non-interactively (3)

Since the api is not protected, even smart users can get data directly from the api. This also means that anyone else can directly access the data, which we don't want to happen. To prevent the API from being exposed to the world, we first secure it in the same way as the application. The preferred scenario is shown in the figure below:

Authenticate with Azure AD interactively and non-interactively (4)

In short, the whole process is the same as before, first authenticate before using the app, then the app can use the api, the app needs to authenticate against the api to get the data. This can be achieved in two different ways:

Use client credentials

As always, the first thing I do when I want to use something I've never used before is to google it, sure enough it's theregithub repositoryExample of using ClientCredentials. I cloned the repository, replaced the settings in App.Config with my own and everything worked as expected.

The base method for acquiring a token from Azure Ad is AcquireTokenAsync(String resource, ClientCredential clientCredential). So first I provide resource parameters. The resource can be an api endpoint or an ApplicationID. I prefer to use the app id.

The second parameter is ClientCredential. usingclient credentialsI need to provide clientId and appKey to access web app in Api. clientId, akaapp-idcan be found by navigating toAzure Active Directory->application registration-> Select your application ->app-id. AppKey must be generated on first use. when stillRegistration Formwindow, go toset up->button-> Add the new key name to the description and click Save. Remember to save the value as it will be hidden forever. If you forget the key value, just generate a new key.
Authenticate with Azure AD interactively and non-interactively (5)

To summarize, here is the code snippet for retrieving the token:

private static async taskGetTokenWithClientCredential(){ varauthority = string.Format(CultureInfo.InvariantCulture, aadInstance,ενοικιαστής); var authContext = νέο AuthenticationContext(authority); var clientCredential = new ClientCredential(clientId resultquontecontencety); doListResourceId, clientCredential );return result.AccessToken;}
Use user password credentials

Well, I google magic again and wow, there's another onegithub repositoryDemonstrate how to authenticate using Azure AD credentialsUser Password Credentials. I clone the repository, run it and get the following:

Authenticate with Azure AD interactively and non-interactively (6)

After some research I found out that I am running AzureAD V2 and this example is based on AzureAD V1. So I wonder if it is also possible to use AAD V2 to get a token with user credentials. Reading the exception message, it clearly states that one of the following parameters is missing.customer claimtheclient secretthere are moregoogle searchIt also indicates that the client key is missing. So how do I provide the client secrets and user credentials? Well, maybe just do a regular post. Before doing this, I choose to check for completed requestsGetTokenAsync()Using fiddler and the client_secret is not provided correctly:

Authenticate with Azure AD interactively and non-interactively (7)

Since I can't find a way to provide the client secret to the AcquireTokenAsync() method, I just manually generate the url and do the usualasync post()useHttpClient()class:

var azureAdEndpoint = νέο Uri(authority + "/oauth2/token");var urlEncodedContent = νέο FormUrlEncodedContent(new[]{ new KeyValuePair("grant_type", "password"), νέο KeyValuePair("scope", "openid"), νέο KeyValuePair( "resource" , todoListResourceId ), new KeyValuePair( "client_id" , todoListResourceId ), //use client id api new KeyValuePair("username", _user), new KeyValuePair("password", _password), νέο KeyValuePair("client_secret", _clientSecret),}); var result = αναμένεται httpClient .PostAsync(azureAdEndpoint, urlEncodedContent); { var content = await result.Content.ReadAsStringAsync(); var authResult = JsonConvertize(BentConvert). επιστροφή authResult.access_token; }

As expected, this gives me the correct token that I can use from my web app to retrieve data from my api.

Authenticate with Azure AD interactively and non-interactively (8)

the source code can be foundhere

sum up

In this post, I look at how to secure web apps and apis hosted in Azure using Azure AD v2. Web applications are secured using regular AAD authentication mechanisms that interactively request credentials from users, while Web applications authenticate silently or non-API using supplied client credentials or user passwords. Securing web applications using this approach is not very dynamic and may be more suitable for existing web applications that need to be easily migrated to Azure. If you need more dynamic and flexible authentication on the other hand, you should consider a solution likeidentity serveror implement your own identity management usingASP.Net Core Identity


At the time of writing this article, April. 4. Microsoft has updated the example git repo and supports the updated versionAzure AD v2.0 and use the Graph API

Resources used in this article:


Top Articles
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated: 09/07/2023

Views: 6140

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.