Beispiel #1
0
 public async Task<DirectoryDataService> buildDirectoryDataServiceAsync()
 {
     var settings = SettingsRepo.GetSettings();
     var authToken = await AuthProvider.GetAuthTokenAsync();
     try
     {
         var directoryDataService = new DirectoryDataService(authToken, settings);
         return directoryDataService;
     }
     catch(Exception ex)
     {
         Debug.WriteLine("Unable to create DirectoryDataService. Error: " + ex.Message);
         return null;
     }
 }
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                // Get the claims required to make further Graph API enquiries about the user
                Claim tenantClaim = incomingPrincipal.FindFirst(TenantIdClaim);
                if (tenantClaim == null)
                {
                    throw new NotSupportedException("Tenant claim not available, role authentication is not supported");
                }
                Claim objectIdentifierClaim = incomingPrincipal.FindFirst(ObjectIdentifierClaim);
                if (objectIdentifierClaim == null)
                {
                    throw new NotSupportedException("Object identifier claim not available, role authentication is not supported");
                }

                string tenantId = tenantClaim.Value;
                string currentUserObjectId = objectIdentifierClaim.Value;

                // Connect to the graph service
                AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantId, _clientId, _password);
                DirectoryDataService graphService = new DirectoryDataService(tenantId, token);

                // Find the user in the graph
// ReSharper disable once ReplaceWithSingleCallToSingleOrDefault - SingleOrDefault not supported on directory service directly
                User currentUser = graphService.directoryObjects.OfType<User>().Where(it => (it.objectId == currentUserObjectId)).SingleOrDefault();
                if (currentUser == null)
                {
                    throw new SecurityException("User cannot be found in graph");
                }

                // Find the groups the user is a member of and add them as role claims
                graphService.LoadProperty(currentUser, "memberOf");
                List<Group> currentRoles = currentUser.memberOf.OfType<Group>().ToList();
                foreach (Group role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role.displayName, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
        public static DirectoryDataService GetInstance(AuthenticationConfiguration config)
        {
            //get the tenantName based on logged in user
            string tenantName = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            AADJWTToken token;
            _tokenLookup.TryGetValue(tenantName, out token);

            if (token == null || token.WillExpireIn(1))
            {
                // Grab a new token

                // retrieve the clientId and password values from the Web.config file
                string clientId = config.ApiClientId;
                string password = config.ApiKey;

                // get a token using the helper, error handling???
                token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password);
                _tokenLookup[tenantName] = token;
            }

            // initialize a graphService instance using the token acquired from previous step
            DirectoryDataService graphService = new DirectoryDataService(tenantName, token);
            return graphService;
        }
        /// <summary>
        /// Method to handle binding redirection exception. This exception means that the 
        /// user's data is located in another data center. This exception's details returns
        /// several urls that may work in this case. At least one url is guaranteed to work
        /// So we need to get all the URLs and try them
        /// </summary>
        /// <param name="parsedException">The binding redirection exception we received</param>
        /// <param name="operation">The operation to try</param>
        private void HandleBindingRedirectionException(ActiveDirectoryParsedException parsedException, Action operation)
        {
            var urls = (from ed in parsedException.Values.ErrorDetail where ed.Name.StartsWith("Url") select ed.Value).ToList();

            // Go thru the error details name\value pair

            // Now try each URL
            foreach (string newUrl in urls)
            {
                // We permanantly change the dataservice to point to the new URL
                // as none of the operations will work on the current url
                Service = new DirectoryDataService(new Uri(string.Format("{0}/{1}", newUrl, Properties.FullTenantAddress)));

                // This adds the default required headers to each request
                AddHeaders();

                try
                {
                    // try the operation
                    operation();

                    // if the operation is successful, break out of the loop
                    // all the subsequent operations will go to the new URL
                    break;
                }
                catch (Exception)
                {
                    // nothing can be done, try next URL
                }
            }
        }
        public void Setup()
        {
            Service = new DirectoryDataService(Properties.ConnectionUri)
                          {
                              IgnoreResourceNotFoundException = true,
                              MergeOption = MergeOption.OverwriteChanges,
                              AddAndUpdateResponsePreference = DataServiceResponsePreference.IncludeContent
                          };

            // This flags ignores the resource not found exception
            // If AzureAD Service throws this exception, it returns null
            // This adds the default required headers to each request
            AddHeaders();
        }