public static async Task <string> GetOAuthTokenFromAAD() { var tenantId = ConfigurationManager.AppSettings["tenantId"]; var clientId = ConfigurationManager.AppSettings["clientId"]; var clientSecret = ConfigurationManager.AppSettings["clientSecret"]; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(AzureEnvironment.AzureGlobalCloud.AuthenticationEndpoint), TokenAudience = new Uri(AzureEnvironment.AzureGlobalCloud.ManagementEndpoint), ValidateAuthority = true }; await ApplicationTokenProvider.LoginSilentAsync( tenantId, clientId, clientSecret, adSettings, TokenCache.DefaultShared); var token = TokenCache.DefaultShared.ReadItems() .Where(t => t.ClientId == clientId) .OrderByDescending(t => t.ExpiresOn) .First(); return(token.AccessToken); }
public void CertAuthWithSPN(string cnnStr) { LiteralCnnString = cnnStr; ServiceClientCredentials svcClientCred = null; X509Certificate2 localCert = null; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCol = store.Certificates; X509Certificate2Collection certsWithSubject = certCol.Find(X509FindType.FindBySubjectName, "TestCertForAuthLib", false); localCert = certsWithSubject[0]; } finally { store.Close(); } ActiveDirectoryServiceSettings aadServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(CloudEndPoints.AADAuthUri.ToString() + TenantId), TokenAudience = CloudEndPoints.AADTokenAudienceUri }; ClientAssertionCertificate certAssertion = new ClientAssertionCertificate(ClientId, localCert); svcClientCred = ApplicationTokenProvider.LoginSilentWithCertificateAsync(TenantId, certAssertion, aadServiceSettings).GetAwaiter().GetResult(); Assert.NotNull(svcClientCred); }
/// <summary> /// Log in to Azure active directory with both user account and authentication credentials provided by the user. This call may display a /// credentials dialog, depending on the supplied client settings and the state of the token cache and user cookies. /// </summary> /// <param name="domain">The domain to authenticate against.</param> /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param> /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param> /// <param name="cache">The token cache to target during authentication.</param> /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns> public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache) { return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings, UserIdentifier.AnyUser, cache)); }
/// <summary> /// Acquire Graph token /// </summary> /// <param name="graphAADServiceSettings"></param> /// <param name="spnClientId"></param> /// <param name="spnSecret"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="psClientId"></param> private void UpdateTokenInfoWithGraphToken(ActiveDirectoryServiceSettings graphAADServiceSettings, string spnClientId = "", string spnSecret = "", string userName = "", string password = "", string psClientId = "") { Task <TokenCredentials> graphAuthResult = null; try { if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { //#if FullNetFx #if net452 graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginSilentAsync(psClientId, this.Tenant, userName, password, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); #endif } else if (!string.IsNullOrWhiteSpace(spnClientId) && !string.IsNullOrWhiteSpace(spnSecret)) { graphAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); } this.TokenInfo[TokenAudience.Graph] = graphAuthResult?.Result; } catch (Exception ex) { Debug.WriteLine(string.Format("Error while acquiring Graph Token: '{0}'", ex.ToString())); // Not all accounts are registered to have access to Graph endpoints. } }
/// <summary> /// Log in to Azure active directory with credentials provided by the user. This call may display a credentials /// dialog, depending on the supplied client settings and the state of the token cache and user cookies. /// </summary> /// <param name="domain">The domain to authenticate against.</param> /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param> /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param> /// <param name="userId">The userid of the desired credentials</param> /// <param name="cache">The token cache to target during authentication.</param> /// <param name="taskScheduler">Scheduler needed to run the task</param> /// <returns></returns> public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings, ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache, Func <TaskScheduler> taskScheduler) { var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache); AuthenticationResult authResult; try { authResult = await authenticationContext.AcquireTokenAsync( serviceSettings.TokenAudience.OriginalString, clientSettings.ClientId, clientSettings.ClientRedirectUri, new PlatformParameters(clientSettings.PromptBehavior), userId, clientSettings.AdditionalQueryParameters); } catch (Exception e) { throw new AuthenticationException( string.Format(CultureInfo.CurrentCulture, "Authentication error while acquiring token: '{0}'", e.Message), e); } var newUserId = new UserIdentifier(authResult.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId); return(new TokenCredentials( new KvTokenProvider(authenticationContext, clientSettings.ClientId, serviceSettings.TokenAudience, newUserId), authResult.TenantId, authResult.UserInfo.DisplayableId)); }
static ActiveDirectoryServiceSettings getActiveDirectoryServiceSettings(string armEndpoint) { var settings = new ActiveDirectoryServiceSettings(); try { var request = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}/metadata/endpoints?api-version=1.0", armEndpoint)); request.Method = "GET"; request.UserAgent = ComponentName; request.Accept = "application/xml"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { var rawResponse = sr.ReadToEnd(); var deserialized = JObject.Parse(rawResponse); var authenticationObj = deserialized.GetValue("authentication").Value <JObject>(); var loginEndpoint = authenticationObj.GetValue("loginEndpoint").Value <string>(); var audiencesObj = authenticationObj.GetValue("audiences").Value <JArray>(); settings.AuthenticationEndpoint = new Uri(loginEndpoint); settings.TokenAudience = new Uri(audiencesObj[0].Value <string>()); settings.ValidateAuthority = loginEndpoint.TrimEnd('/').EndsWith("/adfs", StringComparison.OrdinalIgnoreCase) ? false : true; } } } catch (Exception ex) { Console.WriteLine(String.Format("Could not get AD service settings. Exception: {0}", ex.Message)); } return(settings); }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!_credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (_tokenProvider != null) { var token = await _tokenProvider.GetAccessTokenAsync(adSettings.TokenAudience.OriginalString); _credentialsCache[adSettings.TokenAudience] = new TokenCredentials(token); } // no token available for communication else { throw new RestException($"Cannot communicate with server. No authentication token available for '{adSettings.TokenAudience}'."); } } await _credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public void AuthExceptionWithNullInnerException() { AuthenticationException authExToBeThrown = null; string authError = "Error Occured"; try { ClientCredential cc = new ClientCredential("SomeClientId", "SomethingSomething"); ActiveDirectoryServiceSettings adSvcSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri("https://randomEndPoint"), TokenAudience = new Uri("https://SomeUri"), ValidateAuthority = true }; var token = ApplicationTokenProvider.LoginSilentAsync("SomeDomain", cc, adSvcSettings).GetAwaiter().GetResult(); } catch (AdalException adalEx) { authExToBeThrown = new AuthenticationException(authError); } Assert.NotNull(authExToBeThrown); Assert.Equal(authError, authExToBeThrown.Message); }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (servicePrincipalLoginInformation != null) { if (servicePrincipalLoginInformation.ClientSecret != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } #if NET45 else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #endif else { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared); } } #if !PORTABLE else if (userLoginInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( userLoginInformation.ClientId, TenantId, userLoginInformation.UserName, userLoginInformation.Password, adSettings, TokenCache.DefaultShared); } #endif #if PORTABLE else if (deviceCredentialInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler); } #endif else if (msiTokenProviderFactory != null) { credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString)); } } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { string name = req.Query["name"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; log.LogInformation("Function called by {UserName}", name); var workspaceId = LAWorkSpaceIDAKV; var clientId = clientIDAKV; var clientSecret = clientSecretAKV; var domain = "AZURE_AD_DOMAIN_NAME"; var authEndpoint = "https://login.microsoftonline.com"; var tokenAudience = "https://api.loganalytics.io/"; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult(); var client = new OperationalInsightsDataClient(creds) { WorkspaceId = workspaceId }; // Log Analytics Kusto query - look for data in the past 10 days string query = @" InformationProtectionLogs_CL | where TimeGenerated >= ago(10d) | where UserId_s == '*****@*****.**' | where ProtectionOwner_s == '*****@*****.**' | where Protected_b == 'true' | where ObjectId_s != 'document1' | where MachineName_s != '' | where ApplicationName_s != 'Outlook' | extend FileName = extract('((([a-zA-Z0-9\\s_:]*\\.[a-z]{1,4}$))|([a-zA-Z0-9\\s_:]*$))', 1, ObjectId_s) | distinct FileName, Activity_s, LabelName_s, TimeGenerated, Protected_b, MachineName_s | sort by TimeGenerated desc nulls last"; // update the query with caller user's email string query1 = query.Replace("*****@*****.**", name); var outputTable = client.Query(query1.Trim()).Tables[0]; // Return results to calling agent as a table return(name != null ? (ActionResult) new OkObjectResult(outputTable) : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { string name = req.Query["name"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; log.LogInformation("AIP Tracking Request for File: {FileName} ", name); var workspaceId = LAWorkSpaceIDAKV; var clientId = clientIDAKV; var clientSecret = clientSecretAKV; var domain = "AZURE_AD_DOMAIN_NAME"; var authEndpoint = "https://login.microsoftonline.com"; var tokenAudience = "https://api.loganalytics.io/"; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult(); var client = new OperationalInsightsDataClient(creds) { WorkspaceId = workspaceId }; string query = @"let doclookup = InformationProtectionLogs_CL | where TimeGenerated >= ago(31d) | where ObjectId_s contains 'AIPFILETOTRACK' and ContentId_g != '' | distinct ContentId_g, ObjectId_s; let accesslookup = InformationProtectionLogs_CL | where Operation_s == 'AcquireLicense' or Activity_s != ''; accesslookup | join kind = inner( doclookup ) on $left.ContentId_g == $right.ContentId_g | extend FileName = extract('((([a-zA-Z0-9\\s_:]*\\.[a-z]{1,4}$))|([a-zA-Z0-9\\s_:]*$))', 1, ObjectId_s1) | project ContentId_g, FileName, AccessedBy = UserId_s, Activity_s, ProtectionOwner_s, TimeGenerated, ProtectionTime_t, ApplicationName_s, IPv4_s, MachineName_s"; // update the query with caller user's document to track string query1 = query.Replace("AIPFILETOTRACK", name); var outputTable = client.Query(query1.Trim()).Tables[0]; return(name != null ? (ActionResult) new OkObjectResult(outputTable) : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache) { var context = (cache == null ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain, serviceSettings.ValidateAuthority) : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain, serviceSettings.ValidateAuthority, cache)); return(context); }
public void AzureEnvironmentDoesNotDuplicateSlash(string inputUri) { var testEnvironment = new ActiveDirectoryServiceSettings { ValidateAuthority = true, TokenAudience = new Uri("https://contoso.com/widgets/"), AuthenticationEndpoint = new Uri(inputUri) }; Assert.Equal(inputUri, testEnvironment.AuthenticationEndpoint.ToString()); }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // BEING COPY FROM FLUENT var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } string host = request.RequestUri.Host; if (host.EndsWith(Environment.KeyVaultSuffix, StringComparison.OrdinalIgnoreCase)) { var resource = new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")); if (credentialsCache.ContainsKey(new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")))) { adSettings.TokenAudience = resource; } else { using (var r = new HttpRequestMessage(request.Method, url)) { var response = await new HttpClient().SendAsync(r).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate != null) { var header = response.Headers.WwwAuthenticate.ElementAt(0).ToString(); var regex = new Regex("authorization=\"([^\"]+)\""); var match = regex.Match(header); adSettings.AuthenticationEndpoint = new Uri(match.Groups[1].Value); regex = new Regex("resource=\"([^\"]+)\""); match = regex.Match(header); adSettings.TokenAudience = new Uri(match.Groups[1].Value); } } } } // END COPY FROM FLUENT if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { credentialsCache[adSettings.TokenAudience] = new DefaultAzureMgmtCredential(this.defaultAzureCredential); } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public DataLakeStorageClient(string accountName, string fileSystem, AzureADSettings azureADSettings) { this.AccountName = accountName; this.AzureADSettings = azureADSettings; AzureADServiceSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", azureADSettings.TenantId)), //TokenAudience = new Uri(string.Format("https://{0}{1}/", accountName, SUFFIX)), TokenAudience = new Uri("https://storage.azure.com"), ValidateAuthority = true }; this.FileSystem = fileSystem; }
public bool RunLAQuery(string tableName) { try { // Get credentials fron config.json var appConfig = new AppConfig(); var credentials = appConfig.GetCredentials(); customerId = credentials["workspaceId"]; clientId = credentials["clientId"]; clientSecret = credentials["clientSecret"]; domain = credentials["domain"]; var authEndpoint = "https://login.microsoftonline.com"; var tokenAudience = "https://api.loganalytics.io/"; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult(); var laClient = new OperationalInsightsDataClient(creds); laClient.WorkspaceId = customerId; var path = new SampleDataPath(); var dirPath = path.GetDirPath(); tableName = tableName.Replace(dirPath, "").Replace(".json", ""); string query = tableName + @"| where TimeGenerated > ago(10d) | limit 100"; var results = laClient.Query(query); var tableCount = results.Tables.Count; if (tableCount > 0) { return(true); } else { return(false); } } catch (Exception ex) { throw new Exception("Calling Log Analytics Error " + ex.Message); } }
private ApplicationInsightsDataClient GetClient() { // Authenticate to log analytics. var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(AuthEndpoint), TokenAudience = new Uri(TokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(Domain, clientId, clientSecret, adSettings).Result; return(new ApplicationInsightsDataClient(creds) { AppId = applicationId }); }
/// <summary> /// Gets service principal based credentials /// </summary> /// <param name="authEnvironmentVariable">Environment variable that points to the file system secured azure auth settings</param> /// <returns>ServiceClientCredentials</returns> public static async Task <ServiceClientCredentials> GetServicePrincipalCredential(string authEnvironmentVariable) { AzureAuthInfo authSettings = Deserialize <AzureAuthInfo>(Environment.GetEnvironmentVariable(authEnvironmentVariable)); var aadSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authSettings.ActiveDirectoryEndpointUrl), TokenAudience = new Uri(authSettings.ManagementEndpointUrl), ValidateAuthority = true }; return(await ApplicationTokenProvider.LoginSilentAsync( authSettings.TenantId, authSettings.ClientId, authSettings.ClientSecret, aadSettings)); }
/// <summary> /// Authenticate to the Kusto Log Analytics instance for build. /// </summary> /// <returns></returns> private OperationalInsightsDataClient GetClient() { // Authenticate to log analytics. var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(AuthEndpoint), TokenAudience = new Uri(TokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(Domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult(); var client = new OperationalInsightsDataClient(creds) { WorkspaceId = workspaceId }; return(client); }
/// <summary> /// Run interactive login /// </summary> /// <param name="tenant"></param> /// <param name="aadServiceSettings"></param> /// <param name="graphAADServiceSettings"></param> private void InteractiveLogin(string tenant, string PsClientId, ActiveDirectoryServiceSettings aadServiceSettings, ActiveDirectoryServiceSettings graphAADServiceSettings) { //#if FullNetFx #if net452 ActiveDirectoryClientSettings clientSettings = new ActiveDirectoryClientSettings() { ClientId = PsClientId, ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = PromptBehavior.Always }; TaskScheduler scheduler; if (SynchronizationContext.Current != null) { scheduler = TaskScheduler.FromCurrentSynchronizationContext(); } else { scheduler = TaskScheduler.Current; } Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginWithPromptAsync(this.Tenant, clientSettings, aadServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; this.ConnectionString.KeyValuePairs[ConnectionStringKeys.UserIdKey] = this.TokenInfo[TokenAudience.Management].CallerId; try { Task <TokenCredentials> graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginWithPromptAsync(this.Tenant, clientSettings, graphAADServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: true)); this.TokenInfo[TokenAudience.Graph] = graphAuthResult.Result; } catch { // Not all accounts are registered to have access to Graph endpoints. } #endif }
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; var url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!_credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (_servicePrincipalLoginInformation != null) { if (_servicePrincipalLoginInformation.ClientSecret != null) { _credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, _servicePrincipalLoginInformation.ClientId, _servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } else { _credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, _servicePrincipalLoginInformation.ClientId, _servicePrincipalLoginInformation.Certificate, _servicePrincipalLoginInformation.CertificatePassword, TokenCache.DefaultShared); } } //else if (_userLoginInformation != null) //Not supported in .Net Core. UserTokenProvider.LoginSilentAsync does not exist //{ // _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( // _userLoginInformation.ClientId, TenantId, _userLoginInformation.UserName, // _userLoginInformation.Password, adSettings, TokenCache.DefaultShared); //} else if (_deviceCredentialInformation != null) { _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( _deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, _deviceCredentialInformation.DeviceCodeFlowHandler); } } await _credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
private static ServiceClientCredentials GetServiceClientCredentials( string clientId, string clientSecret, string domain, string authEndpoint, string tokenAudience) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; var serviceClientCredentials = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings) .GetAwaiter().GetResult(); return(serviceClientCredentials); }
protected static ServiceClientCredentials LoginUsingAAD() { var appId = "{appId}"; var clientId = "{aadClientAppId}"; var clientSecret = "{aadAppkey}"; var domain = "{aadTenantId}"; var authEndpoint = "https://login.microsoftonline.com"; var tokenAudience = "https://api.applicationinsights.io/"; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; // Authenticate with client secret (app key) return(ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult()); }
public async static Task <Microsoft.Rest.ServiceClientCredentials> AzureAuthenticateAsync() { try { ActiveDirectoryServiceSettings s = new ActiveDirectoryServiceSettings(); s.AuthenticationEndpoint = new Uri(AzS_ActiveDirectory); s.TokenAudience = new Uri(AzS_ActiveDirectoryResourceID); s.ValidateAuthority = true; var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(AzS_TenantID, AzS_ClientID, AzS_SecretKey, s); return(serviceCreds); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.ReadLine(); return(null); } }
private static void LoginWithPromptAsync( Dictionary <TokenAudience, TokenCredentials> tokens, string domain, TestEndpoints endpoints) { var mgmSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.AADTokenAudienceUri }; var grpSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.GraphTokenAudienceUri }; var clientSettings = new ActiveDirectoryClientSettings() { ClientId = TestEnvironment.ClientIdDefault, ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior = PromptBehavior.Auto }; var mgmAuthResult = (TokenCredentials)UserTokenProvider .LoginWithPromptAsync(domain, clientSettings, mgmSettings) .ConfigureAwait(false) .GetAwaiter().GetResult(); try { var graphAuthResult = (TokenCredentials)UserTokenProvider .LoginWithPromptAsync(domain, clientSettings, grpSettings) .GetAwaiter().GetResult(); tokens[TokenAudience.Graph] = graphAuthResult; } catch { // Not all accounts are registered to have access to Graph endpoints. } tokens[TokenAudience.Management] = mgmAuthResult; }
public async Task <Table> RunLAQuery(string domain, string clientId, string clientSecret, string workspaceId) { var authEndpoint = "https://login.microsoftonline.com"; var tokenAudience = "https://api.loganalytics.io/"; var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authEndpoint), TokenAudience = new Uri(tokenAudience), ValidateAuthority = true }; var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult(); var LAclient = new OperationalInsightsDataClient(creds) { WorkspaceId = workspaceId }; // Log Analytics Kusto query - look for user data in the past 24 hours string query = @" let lookback = timespan(24h); let doclookup = InformationProtectionLogs_CL | where ContentId_g != '' and ObjectId_s != '' and TimeGenerated >= ago(90d) | distinct ContentId_g, ObjectId_s; let accesslookup = InformationProtectionLogs_CL | where TimeGenerated >= ago(lookback) | where Activity_s == 'AccessDenied' | extend AccessCount = 1; accesslookup | join kind = inner( doclookup ) on $left.ContentId_g == $right.ContentId_g | extend FileName = extract('((([^\\/\\\\]*\\.[a-z]{1,4}$))|([[^\\/\\\\]*$))', 1, ObjectId_s1) | summarize AccessCount = sum(AccessCount) by ContentId_g, FileName, LabelName_s, UserId_s, ProtectionOwner_s, TimeGenerated, ProtectionTime_t, IPv4_s, Activity_s, Operation_s"; var outputTable = await LAclient.QueryAsync(query.Trim()); return(outputTable.Tables[0]); }
private static ServiceClientCredentials GetClientCredentials() { var credential = new ClientCredential( GetEnvironmentVariable("clientId"), GetEnvironmentVariable("clientSecret") ); var activeDirectoryServiceSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = ActiveDirectoryServiceSettings.Azure.AuthenticationEndpoint, ValidateAuthority = ActiveDirectoryServiceSettings.Azure.ValidateAuthority, TokenAudience = ActiveDirectoryServiceSettings.Azure.TokenAudience }; return(ApplicationTokenProvider. LoginSilentAsync( GetEnvironmentVariable("domain"), credential, activeDirectoryServiceSettings) .GetAwaiter() .GetResult()); }
/// <summary> /// Gets service principal based credentials /// </summary> /// <param name="authEnvironmentVariable">Environment variable that points to the file system secured azure auth settings</param> /// <returns>ServiceClientCredentials</returns> public static async Task <ServiceClientCredentials> GetServicePrincipalCredential(string authEnvironmentVariable) { var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }; AzureAuthInfo authSettings = JsonSerializer.Deserialize <AzureAuthInfo>(File.ReadAllText(Environment.GetEnvironmentVariable(authEnvironmentVariable)), jsonOptions); var aadSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(authSettings.ActiveDirectoryEndpointUrl), TokenAudience = new Uri(authSettings.ManagementEndpointUrl), ValidateAuthority = true }; return(await ApplicationTokenProvider.LoginSilentAsync( authSettings.TenantId, authSettings.ClientId, authSettings.ClientSecret, aadSettings)); }
private static async Task LoginServicePrincipalAsync( Dictionary <TokenAudience, TokenCredentials> tokens, string domain, string servicePrincipalId, string key, TestEndpoints endpoints) { var mgmSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.AADTokenAudienceUri }; var mgmAuthResult = (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(domain, servicePrincipalId, key, mgmSettings) .ConfigureAwait(false); var grpSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.GraphTokenAudienceUri }; try { var graphAuthResult = (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(domain, servicePrincipalId, key, grpSettings) .ConfigureAwait(false); tokens[TokenAudience.Graph] = graphAuthResult; } catch { // Not all accounts are registered to have access to Graph endpoints. } tokens[TokenAudience.Management] = mgmAuthResult; }
private GraphRbacManagementClient GetGraphClient(MockContext context) { var environment = TestEnvironmentFactory.GetTestEnvironment(); string tenantId = environment.Tenant; if (HttpMockServer.Mode == HttpRecorderMode.Record) { HttpMockServer.Variables[TenantIdKey] = tenantId; string password; string spnClientId; string spnSecret; var connStr = environment.ConnectionString; connStr.KeyValuePairs.TryGetValue(ConnectionStringKeys.PasswordKey, out password); connStr.KeyValuePairs.TryGetValue(ConnectionStringKeys.ServicePrincipalKey, out spnClientId); connStr.KeyValuePairs.TryGetValue(ConnectionStringKeys.ServicePrincipalSecretKey, out spnSecret); var graphAadServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(environment.Endpoints.AADAuthUri + environment.Tenant), TokenAudience = environment.Endpoints.GraphTokenAudienceUri }; var accessToken = ApplicationTokenProvider .LoginSilentAsync(environment.Tenant, spnClientId, spnSecret, graphAadServiceSettings) .ConfigureAwait(false) .GetAwaiter() .GetResult(); environment.TokenInfo[TokenAudience.Graph] = accessToken as TokenCredentials; } var client = context.GetGraphServiceClient <GraphRbacManagementClient>(environment); client.TenantID = tenantId; return(client); }