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.
Before you can connect to the website using the credentials, the application must also be registered in Azure AD -> Application Registration.
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:
- Azure Active Directory->application registration-> select application ->set up->required permitslast clickPermission granted->Corporate application
- 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.
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:
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.
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:
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:
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.
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
notes
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:
https://github.com/Azure-Samples/active-directory-dotnet-native-headless
https://github.com/Azure-Samples/active-directory-dotnet-daemon
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d54c668f-d8e3-4662-b124-d9abc3176c8c/http-post-body-parameters-to-get-oauth2-token?forum=azurelogicapps
https://carldesouza.com/httpclient-getasync-postasync-sendasync-c/
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/issues/57