/// <summary> /// Methods for getting a token from ACS /// Updated 10/21, to use Active Directory Authn Library (ADAL) /// Method uses OAuth Authorization Code Grant flow (3-legged OAuth) /// ADAL package avaialble from https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/1.0.0 /// </summary> public static AADJWTToken GetAuthorizationToken(string tenantName, string appPrincipalId, Uri appUri) { string authString = String.Format(StringConstants.AzureADSTSURL, tenantName); AuthenticationContext authenticationContext = new AuthenticationContext(authString); try { AuthenticationResult authenticationResult = authenticationContext.AcquireToken(StringConstants.GraphPrincipalId.ToString(), appPrincipalId, appUri); if (authenticationResult != null) { AADJWTToken token = new AADJWTToken(); token.AccessToken = authenticationResult.AccessToken; token.TokenType = authenticationResult.AccessTokenType; token.ExpiresOn = authenticationResult.ExpiresOn.UtcTicks; token.AdalToken = authenticationResult; return(token); } else { return(null); } } catch (Exception e) { //Console.WriteLine("Exception: " + e.Message + " " + e.InnerException); return(null); } }
/// <summary> /// Function for getting a token from ACS using Application Service principal Id and Password. /// </summary> public static AADJWTToken GetAuthorizationToken(string tenantName, string appPrincipalId, string password) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format(StringConstants.AzureADSTSURL, tenantName)); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string postData = "grant_type=client_credentials"; postData += "&resource=" + HttpUtility.UrlEncode(StringConstants.GraphPrincipalId); postData += "&client_id=" + HttpUtility.UrlEncode(appPrincipalId); postData += "&client_secret=" + HttpUtility.UrlEncode(password); byte[] data = encoding.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } using (var response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AADJWTToken)); AADJWTToken token = (AADJWTToken)(ser.ReadObject(stream)); return(token); } } }
public ActionResult List() { /*HELPER CONSTRUCTOR*/ //get the tenantName string tenantName = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; // retrieve the clientId and password values from the Web.config file string clientId = ConfigurationManager.AppSettings["AppPrincipalId"]; string password = ConfigurationManager.AppSettings["Password"]; /*NEEDS TO BE CACHED*/ // get a token using the helper AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password); // initialize a graphService instance using the token acquired from previous step DirectoryDataService graphService = new DirectoryDataService(tenantName, token); // get Users var users = graphService.users; QueryOperationResponse <User> response; response = users.Execute() as QueryOperationResponse <User>; List <User> userList = response.ToList(); ViewBag.userList = userList; // For subsequent Graph Calls, the existing token should be used. // The following checks to see if the existing token is expired or about to expire in 2 mins // if true, then get a new token and refresh the graphService // int tokenMins = 2; if (token.IsExpired || token.WillExpireIn(tokenMins)) { AADJWTToken newToken = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password); token = newToken; graphService = new DirectoryDataService(tenantName, token); } // get tenant information var tenant = graphService.tenantDetails; QueryOperationResponse <TenantDetail> responseTenantQuery; responseTenantQuery = tenant.Execute() as QueryOperationResponse <TenantDetail>; List <TenantDetail> tenantInfo = responseTenantQuery.ToList(); ViewBag.OtherMessage = "User List from tenant: " + tenantInfo[0].displayName; return(View(userList)); }