Azure Active Directory (Azure AD) is a cloud-based identity and access management service provided by Microsoft, which allows users of an organization to sign in and access various resources such as Microsoft Office 365, the Azure portal, and many other SaaS applications.
Nowadays, Azure AD has been used as a standard approach for authenticating various office365 based applications, allowing it to work with a user's existing credentials. So, if you are developing applications that are deployed in the Azure environment, then the authentication mechanism is Azure AD instead of creating a custom authentication page and maintaining it
Recently we were working on a project where we needed access to a WCF service deployed on Azure in a .Net application. This worked fine when accessed anonymously, but we faced numerous challenges while making it work with Azure Active Directory Authentication
In this article, I will mention the steps one has to follow to carry out Azure Active Directory authentication on an application developed using .Net and consuming the WCF service or any app deployed on Azure.
I will also be sharing the steps on how to access a secure Azure App using JavaScript
For using Azure Authentication, your organization's Active Directory should be synced with Azure. Let's first see how to enable AD authentication on an Azure Web App









https:// WebAppName.azurewebsites.net
https:// WebAppName.azurewebsites.net/ WCFServiceName.svc
Here WebAppName is the name of your AzureApp created for service deployment.






Note: If the key you generated contains any special characters (+, [], etc.) then generate a new key as it will not work.


https://WebAppName.azurewebsites.net/WCFServiceName.svc

Click on configure
Now using Add URI add https://WebAppName.azurewebsites.net/.auth/login/aad/callback
Here WebAppName is the name of your AzureApp created for service deployment.


Copy the OAuth 2.0 Token Endpoint (V1) Url which is the AzureAuthUrl https://login.microsoftonline.com//oauth2/token

For carrying out Azure AD authentication in .Net applications, we will need the below information which we had generated in the above steps:
Copy these values in the code snippet, as described below. This code will carry out an HTTP web request using the auth URL with all parameters passed in POST and gives us access token, which will be added as Authorization header in the service call using .Net application.
//Here is the code that will give you the Access Token which will be passed to the service call.
string postParameters;
string authURL = https://login.microsoftonline.com//oauth2/token?api-version1.0;
string grant_type = "client_credentials";
string clientID = “ApplicationID”;
string clientCode = “client secret key”;
string resourceURL = “https%3A%2F%2Fwcfservice.azurewebsites.net%2FService.svc”;
postParameters = "grant_type=" + grant_type + "&client_id=" + clientID + "&client_secret=" + clientCode + "&resource=" + resourceURL + "";
var dataToSend = Encoding.UTF8.GetBytes(parameters);
var req = System.Net.HttpWebRequest.Create(authURL);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.ContentLength = dataToSend.Length;
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = req.GetResponse();
var readStream = new StreamReader(response, Encoding.UTF8);
string data = readStream.ReadToEnd();
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(result)
If json.Count > 0 Then
clienttoken = json["access_token"]
End If
//Sample Service Call to a method in which the token generated above is passed
var req = HttpWebRequest.Create(serviceUrl);
req.ContentType = "application/json";
req.Headers("Authorization") = "Bearer " + clienttoken;
req.Method = "GET"
var response = req.GetResponse();
var readStream = new StreamReader(response, Encoding.UTF8);
string data = readStream.ReadToEnd();
This will be helpful in case you have developed any custom web service and deployed it in Azure and need to access the data in office 365 environment like Project Online; then, it can be assessed using JavaScript embedded on a page.
1. Reference adal.min.js for azure authentication in your JavaScript file. You can download the js from https://secure.aadcdn.microsoftonline-p.com/lib/1.0.17/js/adal.min.js
2. Ensure you have added the web URL of your page where you will be adding your custom js for authentication under Add Redirect Url of configuration steps.
3. Get the authentication token
a. Set the attribute values under the config array variable:
i. Tenant: Use the tenantID from the Endpoint URL copied in step 6 above.
ii. clientId: Application ID of Azure App copied in step 4 above
iii. redirectUri : Reply URL added under Add Redirect Url step 5 above.
b. Call GetToken method to generate the authentication token.
c. Use the generated access token in the service call.
var config = {
instance: “https://login.microsoftonline.com/”,
tenant: tenantId,
clientId: clientId,
redirectUri: ‘Reply url added’
cacheLocation: 'localStorage'
};
Function GetToken{
var authContext = new AuthenticationContext(config);
// save tokens if this is a return from AAD
authContext.handleWindowCallback();
//Get user
var user = authContext.getCachedUser();
// attempt callback
if (user) {
// acquire user token
authContext.acquireToken(authContext.config.clientId, function (error, token) {
if (error || !token) {
console.log(error);
return;
}
accessToken = token;
});
}
else if (authContext.getLoginError()) {
// error logging in
console.log("Error logging in", authContext.getLoginError());
}
else {
// not logged in
console.log("Logging in");
authContext.login();
}
}
function servicecall(url, data, successCallback, errorCallback)
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
success: successCallback,
contentType: "application/json",
headers: {
'Authorization': 'Bearer ' + accessToken,
},
error: errorCallback,
dataType: "json"
});
Here url is the Url to the method call of the webservice/app deployed under Azure.
Now, you are ready to carry out Azure Active Directory authentication for an Azure service app called in any JavaScript-enabled Office 365 application.
Happy Coding!!