private async static Task<string> GetAccessTokenAsync(AuthenticationContext context, string[] scope) { if (AuthenticationParentUiContext == null) { throw new InvalidOperationException("The authentication parent is invalid"); } AuthenticationResult result = await context.AcquireTokenAsync( scope: scope, additionalScope: null, clientId: ClientId, redirectUri: RedirectUri, parameters: AuthenticationParentUiContext); if (!string.IsNullOrEmpty(result.Token)) { AccessToken = result.Token; LoggedInUser = result.UserInfo.Name; LoggedInUserEmail = result.UserInfo.DisplayableId; LastTenantId = result.TenantId; } else { return null; } return AccessToken; }
public async Task<IAuthToken> GetAuthTokenAsync() { //ClearAllTokensCache(); var settings = this.SettingsRepo.GetSettings(); var authenticationContext = new AuthenticationContext(settings.LoginURL); var result = await authenticationContext.AcquireTokenAsync(settings.DirectoryServiceURL, settings.ClientID); if(result.Status == AuthenticationStatus.Succeeded) { IAuthToken aadToken = new AADJWTToken(); aadToken.AccessToken = result.AccessToken; return aadToken; } else { throw new Exception(result.Error + " " + result.ErrorDescription); } }
// GET: /<controller>/ public async Task <IActionResult> Index(string projectname) { AuthenticationResult result = null; List <ComputationInfoParticipant> projectParticipantsList = new List <ComputationInfoParticipant>(); if (string.IsNullOrEmpty(projectname)) { projectname = string.Empty; } try { // Because we signed-in already in the WebApp, the userObjectId is known string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; // Using ADAL.Net, get a bearer token to access the MRSDistComp Web APIs AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.CentralRegistryAuthority, new NaiveSessionCache(userObjectID, HttpContext.Session)); ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret); result = await authContext.AcquireTokenAsync(AzureAdOptions.Settings.CentralRegistryResourceAppId, credential); // Retrieve the participant list. HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.CentralRegistryBaseAddress + "/api/GetProjectParticipants"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); request.Content = new StringContent(JsonConvert.SerializeObject(new { projectname = projectname }), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.SendAsync(request); // Return the participants' in the view. if (response.IsSuccessStatusCode) { List <Dictionary <String, String> > responseElements = new List <Dictionary <String, String> >(); JsonSerializerSettings settings = new JsonSerializerSettings(); String responseString = await response.Content.ReadAsStringAsync(); JObject responseJObject = JObject.Parse(responseString); // This is based on the Web API JSON. List of lists of the Result. IList <JToken> rows = responseJObject["outputParameters"]["Result"].Children().ToList(); // serialize JSON results into .NET objects foreach (JToken row in rows) { foreach (JToken column in row) { ComputationInfoParticipant projectParticipant = new ComputationInfoParticipant(); projectParticipant.Id = column[0].ToString(); projectParticipant.ComputationInfoName = column[1].ToString(); projectParticipant.ParticipantName = column[2].ToString(); projectParticipant.IsEnabled = column[3].ToString(); projectParticipantsList.Add(projectParticipant); } } return(View(projectParticipantsList)); } else { // // If the call failed with access denied, then drop the current access token from the cache, // and show the user an error indicating they might need to sign-in again. // if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { var cachedTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.CentralRegistryResourceAppId); foreach (TokenCacheItem tci in cachedTokens) { authContext.TokenCache.DeleteItem(tci); } ViewBag.ErrorMessage = "UnexpectedError"; ComputationInfoParticipant newProjectParticipant = new ComputationInfoParticipant(); newProjectParticipant.Id = "(No participants have enrolled in a project)"; projectParticipantsList.Add(newProjectParticipant); return(View(projectParticipantsList)); } } } catch (Exception ex) { if (HttpContext.Request.Query["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // return(new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme)); } // // The user needs to re-authorize. Show them a message to that effect. // ComputationInfoParticipant newProjectParticipant = new ComputationInfoParticipant(); newProjectParticipant.Id = "(Sign-in required to view project particpants.)"; projectParticipantsList.Add(newProjectParticipant); ViewBag.ErrorMessage = "AuthorizationRequired" + ex.Message; return(View(projectParticipantsList)); } // // If the call failed for any other reason, show the user an error. // return(View("Error")); }
public static async Task <EmbedConfig> GetEmbedReportConfigData(string clientId, string groupId, string username, string password, string authorityUrl, string resourceUrl, string apiUrl, string reportUniqueId, string reportName, ServiceContext serviceContext, IServiceEventSource serviceEventSource) { ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource); var result = new EmbedConfig(); var roles = ""; try { var error = GetWebConfigErrors(clientId, groupId, username, password); if (error != null) { result.ErrorMessage = error; return(result); } // Create a user password cradentials. var credential = new UserPasswordCredential(username, password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(authorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential); if (authenticationResult == null) { result.ErrorMessage = "Authentication Failed."; return(result); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials)) { // Get a list of reports. var reports = await client.Reports.GetReportsInGroupAsync(groupId); Report report; if (string.IsNullOrEmpty(reportName)) { // Get the first report in the group. report = reports.Value.FirstOrDefault(); } else { report = reports.Value.FirstOrDefault(r => r.Name.Equals(reportName)); } if (report == null) { result.ErrorMessage = $"PowerBI Group has no report registered for Name[{reportName}]."; return(result); } var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(groupId, report.DatasetId); result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired; result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired; GenerateTokenRequest generateTokenRequestParameters; // This is how you create embed token with effective identities if ((result.IsEffectiveIdentityRequired != null && result.IsEffectiveIdentityRequired == true) && (result.IsEffectiveIdentityRolesRequired != null && result.IsEffectiveIdentityRolesRequired == true) && !string.IsNullOrEmpty(username)) { var rls = new EffectiveIdentity(username, new List <string> { report.DatasetId }); if (!string.IsNullOrWhiteSpace(roles)) { var rolesList = new List <string>(); rolesList.AddRange(roles.Split(',')); rls.Roles = rolesList; } // Generate Embed Token with effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> { rls }); } else { // Generate Embed Token for reports without effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); } var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(groupId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { serviceEventSourceHelper.ServiceMessage(serviceContext, $"Embed Report - Error during user authentication for report - Result=[{tokenResponse.ToString()}]"); result.ErrorMessage = "Failed to authenticate user for report request"; return(result); } // Generate Embed Configuration. result.EmbedToken = tokenResponse; result.EmbedUrl = report.EmbedUrl; result.Id = report.Id; return(result); } } catch (HttpOperationException exc) { result.ErrorMessage = string.Format($"Status: {exc.Response.StatusCode} Response Content: [{exc.Response.Content}] RequestId: {exc.Response.Headers["RequestId"].FirstOrDefault()}"); } catch (Exception exc) { result.ErrorMessage = exc.ToString(); } return(result); }
/// <summary> /// Gets an Access token for the given resource on behalf of the user in the provided access token /// </summary> /// <param name="userAccessToken">The access token</param> /// <param name="tenantId">Tenant ID</param> /// <param name="resource">Resource ID</param> /// <param name="tokenCachingOptions">Token caching options</param> /// <returns>Authentication result which contains on behalf of token</returns> public async Task <AuthenticationResult> GetAccessTokenForResourceFromUserTokenAsync( string userAccessToken, string tenantId, string resource, TokenCachingOptions tokenCachingOptions) { trace.TraceInformation("Start GetAccessTokenForResourceFromUserTokenAsync"); var aadInstance = GetAADInstance(this.aadClientConfig.AADInstance, tenantId); var exceptions = new List <Exception>(); var thumbprints = this.aadClientConfig.ClientCertificateThumbprintList; var userName = this.GetUserName(); AuthenticationResult result = null; try { if (tokenCachingOptions == TokenCachingOptions.PreferCache && this.TryGetAccessToken(resource, tenantId, userName, out result)) { trace.TraceInformation("Retrieved access token from cache."); return(result); } foreach (var thumbprint in thumbprints) { try { // Construct context var authority = this.aadClientConfig.AADInstance.FormatWithInvariantCulture(tenantId); var context = new AuthenticationContext(authority, false); context.CorrelationId = new Guid(); // Construct client assertion certificate var certificate = this.certificateManager.FindByThumbprint(thumbprint, StoreName.My, StoreLocation.LocalMachine); var clientAssertionCertificate = new ClientAssertionCertificate(this.aadClientConfig.ClientId, certificate); // User Assertion if (string.IsNullOrEmpty(userAccessToken)) { trace.TraceInformation("Calling AcquireTokenAsync without User Assertion."); result = await context.AcquireTokenAsync(resource, clientAssertionCertificate); } else { trace.TraceInformation("Calling AcquireTokenAsync with User Assertion."); var userAssertion = new UserAssertion(TrimBearerToken(userAccessToken)); result = await context.AcquireTokenAsync(resource, clientAssertionCertificate, userAssertion); } trace.TraceInformation($"Requesting access token for Resource: '{resource}', AADInstance: '{aadInstance}', ClientID: '{this.aadClientConfig.ClientId}, CorrelationId: '{context.CorrelationId}'"); if (!string.IsNullOrEmpty(userName)) { // Set Cache this.SetAccessTokenCache(this.graphConfig.GraphResourceId, this.graphConfig.GraphTenant, userName, result); } return(result); } catch (AdalServiceException ex) { // trace.TraceWarning($"AdalServiceException: error code- {ex.ErrorCode}, error message- {ex.Message}"); exceptions.Add(ex); //} //catch (CertificateNotFoundException ex) //{ // exceptions.Add(ex); } catch (Exception ex) { exceptions.Add(ex); break; } } } catch (AdalException exception) { HandleAzureActiveDirectoryClientException(exception); return(null); } throw new AggregateException($"Could not successfully acquire certificate using thumbprints: {string.Join(", ", aadClientConfig.ClientCertificateThumbprintList)}", exceptions); }
public static async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log) { log.LogInformation($"FetchADFMetrics function executed at: {DateTime.Now}"); // Set variables var tenantID = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process); var applicationId = Environment.GetEnvironmentVariable("ApplicationId", EnvironmentVariableTarget.Process); var authenticationKey = Environment.GetEnvironmentVariable("AuthenticationKey", EnvironmentVariableTarget.Process); var subscriptionId = Environment.GetEnvironmentVariable("SubscriptionId", EnvironmentVariableTarget.Process); var resourceGroup = Environment.GetEnvironmentVariable("ResourceGroup", EnvironmentVariableTarget.Process); var minuteInterval = Environment.GetEnvironmentVariable("MinuteInterval", EnvironmentVariableTarget.Process); var newRelicInsightsInsertAPIKey = Environment.GetEnvironmentVariable("NewRelicInsightsInsertAPIKey", EnvironmentVariableTarget.Process); var newRelicAccountId = Environment.GetEnvironmentVariable("NewRelicAccountId", EnvironmentVariableTarget.Process); // Authenticate and create a data factory management client var context = new AuthenticationContext("https://login.windows.net/" + tenantID); ClientCredential cc = new ClientCredential(applicationId, authenticationKey); AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result; ServiceClientCredentials cred = new TokenCredentials(result.AccessToken); var factoryClient = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId }; // Get list of factories List <Factory> factories = new List <Factory>(); string nextPageLink = null; do { try { Microsoft.Rest.Azure.IPage <Factory> newFactories; if (string.IsNullOrEmpty(nextPageLink)) { newFactories = await factoryClient.Factories.ListByResourceGroupAsync(resourceGroup); } else { newFactories = await factoryClient.Factories.ListByResourceGroupNextAsync(nextPageLink); } nextPageLink = newFactories.NextPageLink; factories.AddRange(newFactories); } catch (Exception e) { log.LogError("Error fetching Factories", e); log.LogError($"Exception type = {e.GetType().Name}"); log.LogError($"Exception message = {e.Message}; source = {e.Source}"); log.LogError($"Exception stack trace = {e.StackTrace}"); return; } }while (!string.IsNullOrEmpty(nextPageLink)); if (factories.Count == 0) { log.LogInformation($"No Factories found in resource group {resourceGroup}"); return; } // Get list of pipeline runs in the last interval of minutes by factory List <PipelineRun> pipelineRuns = new List <PipelineRun>(); nextPageLink = null; foreach (var f in factories) { do { try { string token = null; do { var updatedPipelineRuns = await factoryClient.PipelineRuns.QueryByFactoryAsync( resourceGroup, f.Name, new RunFilterParameters( DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow, token ) ); pipelineRuns.AddRange(updatedPipelineRuns.Value); token = updatedPipelineRuns.ContinuationToken; }while (!string.IsNullOrEmpty(token)); } catch (Exception e) { log.LogError("Error fetching PipelineRuns", e); log.LogError($"Exception type = {e.GetType().Name}"); log.LogError($"Exception message = {e.Message}; source = {e.Source}"); log.LogError($"Exception stack trace = {e.StackTrace}"); return; } }while (!string.IsNullOrEmpty(nextPageLink)); } if (pipelineRuns.Count == 0) { log.LogInformation($"No pipelineRun updates in the last {minuteInterval} minutes"); return; } // Insert PipelineRun objects into New Relic Insights var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("X-Insert-Key", newRelicInsightsInsertAPIKey); httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json"); foreach (var p in pipelineRuns) { var jobj = new JObject(p); jobj.Add("eventType", "ADFPipelineRun"); // eventType is required //Need to convert DateTimes into Unix timestamps in seconds or milliseconds if (p.LastUpdated.HasValue) { jobj["LastUpdated"] = ((DateTimeOffset)p.LastUpdated.Value.ToUniversalTime()).ToUnixTimeSeconds(); jobj["timestamp"] = ((DateTimeOffset)p.LastUpdated.Value.ToUniversalTime()).ToUnixTimeSeconds(); // If LastUpdated is populated, use this for the Insights timestamp } if (p.RunStart.HasValue) { jobj["RunStart"] = ((DateTimeOffset)p.RunStart.Value.ToUniversalTime()).ToUnixTimeSeconds(); } if (p.RunEnd.HasValue) { jobj["RunEnd"] = ((DateTimeOffset)p.RunEnd.Value.ToUniversalTime()).ToUnixTimeSeconds(); } try { var response = await httpClient.PostAsJsonAsync($"https://insights-collector.newrelic.com/v1/accounts/{newRelicAccountId}/events", p); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); log.LogInformation("Event insertion into Insights succeeeded"); log.LogInformation(responseBody); } catch (Exception e) { log.LogError("Error inserting PipelineRun into Insights", e); log.LogError($"Exception type = {e.GetType().Name}"); log.LogError($"Exception message = {e.Message}; source = {e.Source}"); log.LogError($"Exception stack trace = {e.StackTrace}"); } } } }
public async Task <string> GetAccessToken(string authority, string resource, string scope) { var context = new AuthenticationContext(authority, TokenCache.DefaultShared); return((await context.AcquireTokenAsync(resource, assertionCert)).AccessToken); }
static async Task PostTodo() { // Get an access token from Azure AD using client credentials. // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each. AuthenticationResult result = null; int retryCount = 0; bool retry = false; do { retry = false; try { // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired. result = await authContext.AcquireTokenAsync(todoListResourceId, certCred); } catch (Exception ex) { AdalException exc = ex as AdalException; if (exc.ErrorCode == "temporarily_unavailable") { retry = true; retryCount++; Thread.Sleep(3000); } Console.WriteLine( String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n", DateTime.Now.ToString(), ex.ToString(), retry.ToString())); } } while ((retry == true) && (retryCount < 3)); if (result == null) { Console.WriteLine("Canceling attempt to contact To Do list service.\n"); return; } // // Post an item to the To Do list service. // // Add the access token to the authorization header of the request. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // Forms encode To Do item and POST to the todo list web api. string timeNow = DateTime.Now.ToString(); Console.WriteLine("Posting to To Do list at {0}", timeNow); string todoText = "Task at time: " + timeNow; HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", todoText) }); HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content); if (response.IsSuccessStatusCode == true) { Console.WriteLine("Successfully posted new To Do item: {0}\n", todoText); } else { Console.WriteLine("Failed to post a new To Do item\nError: {0}\n", response.ReasonPhrase); } }
async Task <string> GetAppToken(string authority, string resource, string scope) { var result = await adalContext.AcquireTokenAsync(resources.AzureRM, new ClientCredential(azureAdOptions.ClientId, azureAdOptions.ClientSecret)).ConfigureAwait(false); return(result.AccessToken); }
public async Task<IActionResult> Post([FromBody]Order order) { bool listenForResponse = Boolean.TryParse(Request.Headers["ImplementAsyncRequestResponseMessaging"], out listenForResponse); var topicClient = new TopicClient(_appSettings.ServiceBusConnectionString, _appSettings.OrderTopicName); try { if(order == null) { return BadRequest(); } var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order))); message.MessageId = Guid.NewGuid().ToString(); if (listenForResponse) { var responseSessionID = order.Id.ToString(); var tenantId = _appSettings.TenantId; var clientId = _appSettings.ClientId; var clientSecret = _appSettings.ClientSecret; var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}"); var result = await context.AcquireTokenAsync( "https://management.core.windows.net/", new ClientCredential(clientId, clientSecret)); var creds = new TokenCredentials(result.AccessToken); var sbClient = new ServiceBusManagementClient(creds) { SubscriptionId = _appSettings.SubscriptionId }; var queueParams = new SBQueue() { DeadLetteringOnMessageExpiration = true, RequiresSession = true, DefaultMessageTimeToLive = TimeSpan.FromMilliseconds(20000) }; await sbClient.Queues.CreateOrUpdateAsync(_appSettings.ResourceGroupName, _appSettings.ServiceBusNamespace, responseSessionID, queueParams); var sessionClient = new SessionClient(_appSettings.ServiceBusConnectionString, responseSessionID); var session = await sessionClient.AcceptMessageSessionAsync(responseSessionID); await topicClient.SendAsync(message); var responseMessage = await session.ReceiveAsync(); if (responseMessage != null) { var orderResponse = JsonConvert.DeserializeObject<OrderResponse>(Encoding.UTF8.GetString(responseMessage.Body)); await session.CompleteAsync(responseMessage.SystemProperties.LockToken); await sbClient.Queues.DeleteAsync(_appSettings.ResourceGroupName, _appSettings.ServiceBusNamespace, responseSessionID); await sessionClient.CloseAsync(); return new JsonResult(orderResponse); } } await topicClient.SendAsync(message); return Ok(); } catch(Exception ex) { return StatusCode(500); } finally { await topicClient.CloseAsync(); } }
/// <summary> /// Get a Microsoft Graph access token from Azure AD. /// </summary> /// <param name="appClientId">Azure AD application client ID</param> /// <returns>An oauth2 access token.</returns> internal async Task <string> GetUserTokenAsync(string appClientId) { // For the first use get an access token prompting the user, after one hour // refresh silently the token if (_tokenForUser == null) { IdentityModel.Clients.ActiveDirectory.AuthenticationResult userAuthnResult = await _azureAdContext.AcquireTokenAsync(MicrosoftGraphResource, appClientId, new Uri(DefaultRedirectUri), new IdentityModel.Clients.ActiveDirectory.PlatformParameters(PromptBehavior.Always, false)); _tokenForUser = userAuthnResult.AccessToken; _expiration = userAuthnResult.ExpiresOn; } if (_expiration <= DateTimeOffset.UtcNow.AddMinutes(5)) { IdentityModel.Clients.ActiveDirectory.AuthenticationResult userAuthnResult = await _azureAdContext.AcquireTokenSilentAsync(MicrosoftGraphResource, appClientId); _tokenForUser = userAuthnResult.AccessToken; _expiration = userAuthnResult.ExpiresOn; } return(_tokenForUser); }
public async Task <ActionResult> Index(string projectname, string projectdesc, string schemaname, string computationtype, string formula, string submitbutton) { if (ModelState.IsValid) { // // Retrieve the user's tenantID and access token since // they are parameters used to call the To Do service. // AuthenticationResult result = null; List <ComputationInfo> computationProjectsList = new List <ComputationInfo>(); try { string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session)); ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret); result = await authContext.AcquireTokenAsync(AzureAdOptions.Settings.CentralRegistryResourceAppId, credential); HttpClient client = new HttpClient(); HttpContent content = null; HttpRequestMessage request = null; // If "Propose" button is clicked if (submitbutton == "Propose") { // Request content for Project proposal content = new StringContent(JsonConvert.SerializeObject(new { projectname = projectname, projectdesc = projectdesc, schemaname = schemaname, computationtype = computationtype, formula = formula, broadcast = true }), System.Text.Encoding.UTF8, "application/json"); request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.CentralRegistryBaseAddress + "/api/ProposeComputation"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); request.Content = content; } // Register computation types in the distcomp package else if (submitbutton == "Register") { // Request content for computation type registration content = new StringContent("{}", Encoding.UTF8, "application/json"); request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.CentralRegistryBaseAddress + "/api/RegisterComputations"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); request.Content = content; } else { // No-op for other actions return(RedirectToAction("Index")); } HttpResponseMessage response = await client.SendAsync(request); // // Return the To Do List in the view. // if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else { // // If the call failed with access denied, then drop the current access token from the cache, // and show the user an error indicating they might need to sign-in again. // if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { var cachedTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.CentralRegistryResourceAppId); foreach (TokenCacheItem tci in cachedTokens) { authContext.TokenCache.DeleteItem(tci); } // // The user needs to re-authorize. Show them a message to that effect. // ComputationInfo newComputationProject = new ComputationInfo(); newComputationProject.ProjectName = "(Sign-in required to view computation projects.)"; computationProjectsList.Add(newComputationProject); ViewBag.ErrorMessage = "UnexpectedError"; return(View(computationProjectsList)); } } } catch { // // The user needs to re-authorize. Show them a message to that effect. // // // The user needs to re-authorize. Show them a message to that effect. // ComputationInfo newComputationProject = new ComputationInfo(); newComputationProject.ProjectName = "(Sign-in required to view computation projects.)"; computationProjectsList.Add(newComputationProject); ViewBag.ErrorMessage = "AuthorizationRequired"; return(View(computationProjectsList)); } // // If the call failed for any other reason, show the user an error. // return(View("Error")); } return(View("Error")); }
public async Task <string> Authenticate() { var token = await _authenticationContext.AcquireTokenAsync(_options.Resource, _clientAssertion).ConfigureAwait(false); return(token.AccessToken); }
private async Task <string> genarateReportAsync() { var result = new EmbedConfig(); try { result = new EmbedConfig { Username = Username, Roles = null }; var error = GetWebConfigErrors(); if (error != null) { result.ErrorMessage = error; errorWrapper.Visible = true; lblError.InnerText = error; //return View(result); } // Create a user password cradentials. var credential = new UserPasswordCredential(Username, Password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential); if (authenticationResult == null) { result.ErrorMessage = "Authentication Failed."; errorWrapper.Visible = true; lblError.InnerText = result.ErrorMessage; } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { // Get a list of reports. var reports = await client.Reports.GetReportsInGroupAsync(GroupId); Report report; if (string.IsNullOrEmpty(ReportId)) { // Get the first report in the group. report = reports.Value.FirstOrDefault(); } else { report = reports.Value.FirstOrDefault(r => r.Id == ReportId); } if (report == null) { result.ErrorMessage = "Group has no reports."; errorWrapper.Visible = true; lblError.InnerText = result.ErrorMessage; } var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(GroupId, report.DatasetId); result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired; result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired; GenerateTokenRequest generateTokenRequestParameters; // This is how you create embed token with effective identities // Generate Embed Token for reports without effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { result.ErrorMessage = "Failed to generate embed token."; errorWrapper.Visible = true; lblError.InnerText = result.ErrorMessage; } // Generate Embed Configuration. result.EmbedToken = tokenResponse; result.EmbedUrl = report.EmbedUrl; result.Id = report.Id; hdnAccessToken.Value = result.EmbedToken.Token; embedUrl.Value = result.EmbedUrl; embedReportId.Value = result.Id; var str = string.Format("openReport();", result.EmbedToken.Token, result.EmbedUrl, result.Id); ScriptManager.RegisterStartupScript(this, this.GetType(), "sas", "openReport();", true); //return View(result); } } catch (HttpOperationException exc) { result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault()); errorWrapper.Visible = true; lblError.InnerText = result.ErrorMessage; } catch (Exception exc) { result.ErrorMessage = exc.ToString(); errorWrapper.Visible = true; lblError.InnerText = result.ErrorMessage; } return(null); }
private static async Task <string> GetToken() { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await context.AcquireTokenAsync(resource, credential); return(result.AccessToken); }
// GET: api/ConditionalAccess public async Task Get() { if (!ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation")) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" }); } AuthenticationResult result = null; // // Use ADAL to get a token On Behalf Of the current user. To do this we will need: // The Resource ID of the service we want to call. // The current user's access token, from the current request's authorization header. // The credentials of this application. // The username (UPN or email) of the user calling the API // ClientCredential clientCred = new ClientCredential(clientId, appKey); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null?ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; string userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId)); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = await authContext.AcquireTokenAsync(caResourceId, clientCred, userAssertion); } catch (AdalServiceException ex) { if (ex.ErrorCode == INTERACTION_REQUIRED) { String claims = null; String error = null; // Extracts the error and claims data from exception JSON String temp = ex.InnerException.InnerException.Message; var output = JsonConvert.DeserializeObject(temp); foreach (var x in (JObject)output) { String jvalue = x.Key; if (jvalue == "claims") { claims = x.Value.ToString(); } if (jvalue == "error") { error = x.Value.ToString(); } } // Clear the token cache authContext.TokenCache.Clear(); HttpResponseMessage myMessage = new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = error, Content = new StringContent(claims) }; throw new HttpResponseException(myMessage); } } catch (AdalException ex) { if (ex.ErrorCode == SERVICE_UNAVAILABLE) { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); // Access token is available in result; String oboAccessToken = result.AccessToken; // // We can now use this access token to accesss our Conditional-Access protected Web API using On-behalf-of // Use this code below to call the downstream Web API OBO // // e.g. // private HttpClient httpClient = new HttpClient(); // httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // HttpResponseMessage response = await httpClient.GetAsync(WebAPI2HttpEndpoint (App ID URI + "/endpoint"); return; }
private void SetupDynamics(IServiceCollection services) { string redisServer = Configuration["REDIS_SERVER"]; string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; string aadTenantId = Configuration["DYNAMICS_AAD_TENANT_ID"]; string serverAppIdUri = Configuration["DYNAMICS_SERVER_APP_ID_URI"]; string clientKey = Configuration["DYNAMICS_CLIENT_KEY"]; string clientId = Configuration["DYNAMICS_CLIENT_ID"]; string ssgUsername = Configuration["SSG_USERNAME"]; string ssgPassword = Configuration["SSG_PASSWORD"]; if (string.IsNullOrEmpty(redisServer)) { services.AddDistributedRedisCache(options => { options.Configuration = redisServer; }); } AuthenticationResult authenticationResult = null; // authenticate using ADFS. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; } services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) => { ServiceClientCredentials serviceClientCredentials = null; if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); serviceClientCredentials = new TokenCredentials(token); } else { serviceClientCredentials = new BasicAuthenticationCredentials() { UserName = ssgUsername, Password = ssgPassword }; } IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials); // set the native client URI if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"])) { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]); } else { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]); } return(client); })); Interfaces.Microsoft.Dynamics.CRM.System context = new Interfaces.Microsoft.Dynamics.CRM.System(new Uri(Configuration["DYNAMICS_ODATA_URI"])); // determine if we have a SSG connection. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", authenticationResult.CreateAuthorizationHeader()); } else { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword)); context.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", "Basic " + credentials); } services.AddSingleton <Interfaces.Microsoft.Dynamics.CRM.System>(context); // add SharePoint. string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"]; string sharePointOdataUri = Configuration["SHAREPOINT_ODATA_URI"]; string sharePointWebname = Configuration["SHAREPOINT_WEBNAME"]; string sharePointAadTenantId = Configuration["SHAREPOINT_AAD_TENANTID"]; string sharePointClientId = Configuration["SHAREPOINT_CLIENT_ID"]; string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"]; string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"]; services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(sharePointServerAppIdUri, sharePointOdataUri, sharePointWebname, sharePointAadTenantId, sharePointClientId, sharePointCertFileName, sharePointCertPassword, ssgUsername, ssgPassword)); // add BCeID Web Services string bceidUrl = Configuration["BCEID_SERVICE_URL"]; string bceidSvcId = Configuration["BCEID_SERVICE_SVCID"]; string bceidUserid = Configuration["BCEID_SERVICE_USER"]; string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"]; services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl)); // add BCEP services var bcep_svc_url = Environment.GetEnvironmentVariable("BCEP_SERVICE_URL"); var bcep_svc_svcid = Environment.GetEnvironmentVariable("BCEP_MERCHANT_ID"); var bcep_svc_hashid = Environment.GetEnvironmentVariable("BCEP_HASH_KEY"); var bcep_base_uri = Environment.GetEnvironmentVariable("BASE_URI"); var bcep_base_path = Environment.GetEnvironmentVariable("BASE_PATH"); var bcep_conf_path = Environment.GetEnvironmentVariable("BCEP_CONF_PATH"); services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_hashid, bcep_base_uri + bcep_base_path + bcep_conf_path)); }
private async Task <AzureToken> GetBearerToken() { var authenticated = new AzureToken(); var authority = AzureManagementAuthority; if (!string.IsNullOrEmpty(_azureAppRegistrationAuthority)) { authority = _azureAppRegistrationAuthority; } if (_spAuth != null) { // Service Principle Authentication. var clientCredential = new ClientCredential(_spAuth.AppId, _spAuth.AppSecret); var context = new AuthenticationContext($"{WindowsLoginAuthority}{_spAuth.TenantId}", false); var tokenResult = await context.AcquireTokenAsync(authority, clientCredential).ConfigureAwait(false); if (tokenResult == null) { throw new InvalidOperationException("Could not authenticate using Service Principle authentication"); } // Set the return Azure Token information. authenticated.Expires = tokenResult.ExpiresOn; authenticated.BearerToken = tokenResult.AccessToken; } else if (_msiAuth != null) { // Msi Authentication. var provider = new AzureServiceTokenProvider(); var token = await provider.GetAccessTokenAsync(authority, _msiAuth.TenantId) .ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { throw new InvalidOperationException("Could not authenticate using Managed Service Identity, ensure the application is running in a secure context"); } var tokenDecoder = new JwtSecurityTokenHandler(); if (!(tokenDecoder.ReadToken(token) is JwtSecurityToken jwtSecurityToken)) { throw new InvalidOperationException("Could not authenticate using Managed Service Identity, ensure the application is running in a secure context"); } // Set the return Azure Token information. authenticated.BearerToken = jwtSecurityToken.RawData; authenticated.Expires = jwtSecurityToken.ValidTo; } else if (_certAuth != null) { //Certificate Authentication var authenticationAuthority = $"{WindowsLoginAuthority}{_certAuth.TenantName}"; var authContext = new AuthenticationContext(authenticationAuthority); var clientAssertionCertificate = new ClientAssertionCertificate(_certAuth.AppId, _certAuth.Certificate); var azureADAppOnlyAuthenticationToken = authContext.AcquireTokenAsync(AzureManagementAuthority, clientAssertionCertificate).GetAwaiter().GetResult(); if (azureADAppOnlyAuthenticationToken == null) { throw new InvalidOperationException("Could not authenticate using Certificate authentication"); } // Set the return Azure Token information. authenticated.BearerToken = azureADAppOnlyAuthenticationToken.AccessToken; authenticated.Expires = azureADAppOnlyAuthenticationToken.ExpiresOn; } else { var jwtSecurityToken = await GetUserAuthToken().ConfigureAwait(false); if (jwtSecurityToken == null) { throw new InvalidOperationException("Could not authenticate using Certificate authentication"); } // Set the return Azure Token information. authenticated.BearerToken = jwtSecurityToken.RawData; authenticated.Expires = jwtSecurityToken.ValidTo; } return(authenticated); }
private void SetupServices(IServiceCollection services) { string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"]; string aadTenantId = _configuration["DYNAMICS_AAD_TENANT_ID"]; string serverAppIdUri = _configuration["DYNAMICS_SERVER_APP_ID_URI"]; string clientKey = _configuration["DYNAMICS_CLIENT_KEY"]; string clientId = _configuration["DYNAMICS_CLIENT_ID"]; string ssgUsername = _configuration["SSG_USERNAME"]; string ssgPassword = _configuration["SSG_PASSWORD"]; AuthenticationResult authenticationResult = null; // authenticate using ADFS. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; } services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://localhost", "http://cannabis-licensing-dev.pathfinder.bcgov", "http://cannabis-licensing-test.pathfinder.bcgov", "http://cannabis-licensing-prod.pathfinder.bcgov", "https://dev.justice.gov.bc.ca", "https://test.justice.gov.bc.ca", "https://justice.gov.bc.ca"); }); }); services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) => { IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(_configuration); return(client); })); // add SharePoint. services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(_configuration)); // add BCeID Web Services string bceidUrl = _configuration["BCEID_SERVICE_URL"]; string bceidSvcId = _configuration["BCEID_SERVICE_SVCID"]; string bceidUserid = _configuration["BCEID_SERVICE_USER"]; string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"]; services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl)); // add BCEP services var bcep_svc_url = _configuration["BCEP_SERVICE_URL"]; var bcep_svc_svcid = _configuration["BCEP_MERCHANT_ID"]; var bcep_svc_hashid = _configuration["BCEP_HASH_KEY"]; var bcep_base_uri = _configuration["BASE_URI"]; var bcep_base_path = _configuration["BASE_PATH"]; var bcep_conf_path = _configuration["BCEP_CONF_PATH"]; services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_hashid, bcep_base_uri + bcep_base_path + bcep_conf_path)); // add the PDF client. string pdf_service_base_uri = _configuration["PDF_SERVICE_BASE_URI"]; string bearer_token = $"Bearer {_configuration["PDF_JWT_TOKEN"]}"; services.AddTransient <PdfClient>(_ => new PdfClient(pdf_service_base_uri, bearer_token)); // add the GeoCoder Client. services.AddTransient <GeocoderClient>(_ => new GeocoderClient(_configuration)); // add the file manager. string fileManagerURI = _configuration["FILE_MANAGER_URI"]; if (!string.IsNullOrEmpty(fileManagerURI)) { var httpClientHandler = new HttpClientHandler(); if (!_env.IsProduction()) // Ignore certificate errors in non-production modes. // This allows you to use OpenShift self-signed certificates for testing. { // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; } var httpClient = new HttpClient(httpClientHandler); // set default request version to HTTP 2. Note that Dotnet Core does not currently respect this setting for all requests. httpClient.DefaultRequestVersion = HttpVersion.Version20; var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions { HttpClient = httpClient }); var initialClient = new FileManagerClient(initialChannel); // call the token service to get a token. var tokenRequest = new TokenRequest() { Secret = _configuration["FILE_MANAGER_SECRET"] }; var tokenReply = initialClient.GetToken(tokenRequest); if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success) { // Add the bearer token to the client. httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}"); var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions() { HttpClient = httpClient }); services.AddTransient <FileManagerClient>(_ => new FileManagerClient(channel)); } } }
public SharePointFileManager(string serverAppIdUri, string odataUri, string webname, string aadTenantId, string clientId, string certFileName, string certPassword, string ssgUsername, string ssgPassword) { OdataUri = odataUri; ServerAppIdUri = serverAppIdUri; WebName = webname; // ensure the webname has a slash. if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/') { WebName = "/" + WebName; } string listDataEndpoint = odataUri + "/_vti_bin/listdata.svc/"; apiEndpoint = odataUri + "/_api/"; this.listData = new LCLBCannabisDEVDataContext(new Uri(listDataEndpoint)); this.apiData = new ApiData(new Uri(apiEndpoint)); if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { // add authentication. var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); // Create the Client cert. X509Certificate2 cert = new X509Certificate2(certFileName, certPassword); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, cert); //ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientAssertionCertificate); task.Wait(); authenticationResult = task.Result; authorization = authenticationResult.CreateAuthorizationHeader(); } else { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword)); authorization = "Basic " + credentials; } apiData.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", authorization); listData.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add( "Authorization", authorization); // create the HttpClient that is used for our direct REST calls. client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); client.DefaultRequestHeaders.Add("Authorization", authorization); var digestTask = GetDigest(client); digestTask.Wait(); string digest = digestTask.Result; client.DefaultRequestHeaders.Add("X-RequestDigest", digest); }
public async Task <HttpResponseMessage> GetCortexLogs(string traceId) { try { if (string.IsNullOrEmpty(traceId)) { throw new Exception($"Invalid traceId {traceId}"); } string authority = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47"; string clientId = "db662dc1-0cfe-4e1c-a843-19a68e65be58"; string redirectUrl = "https://microsoft/kustoclient"; AuthenticationContext authContext = new AuthenticationContext(authority); AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(DatabaseConstants.Uxo_Connection, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Always)).GetAwaiter().GetResult(); Console.WriteLine(authenticationResult.AccessToken); var kustoConnectionStringBuilder = new KustoConnectionStringBuilder(DatabaseConstants.Uxo_Connection) { FederatedSecurity = true, InitialCatalog = "NetDefaultDB", Authority = authority, UserToken = authenticationResult.AccessToken }; var queryProvider = KustoClientFactory.CreateCslQueryProvider(kustoConnectionStringBuilder); zone = await uxoLoggerController.FetchZoneForTraceId(traceId, queryProvider); if (string.IsNullOrEmpty(zone)) { throw new Exception($"No Zone found for {traceId}"); } if (string.Equals(zone, "WestUS2", StringComparison.InvariantCultureIgnoreCase)) { Database = DatabaseConstants.Cortex_PPE_Database; } else { Database = DatabaseConstants.Cortex_Prod_Database; } var CortexTraceResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Cortex_Connection, Database, GetQuery("CortexTraceMDS", traceId), queryProvider); var CortexMonitoredScopeResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Cortex_Connection, Database, GetQuery("CortexMonitoredScopeMDS", traceId), queryProvider); var result = new List <DatabaseResult>() { CortexTraceResult, CortexMonitoredScopeResult }; return(new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(result)) }); } catch (Exception e) { Console.Write(e); return(new HttpResponseMessage() { Content = new StringContent(e.Message), StatusCode = System.Net.HttpStatusCode.InternalServerError }); } }
public SharePointFileManager(IConfiguration Configuration) { // create the HttpClient that is used for our direct REST calls. _CookieContainer = new CookieContainer(); _HttpClientHandler = new HttpClientHandler() { UseCookies = true, AllowAutoRedirect = false, CookieContainer = _CookieContainer }; _Client = new HttpClient(_HttpClientHandler); _Client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); // SharePoint configuration settings. string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"]; string sharePointOdataUri = Configuration["SHAREPOINT_ODATA_URI"]; string sharePointWebname = Configuration["SHAREPOINT_WEBNAME"]; string sharePointNativeBaseURI = Configuration["SHAREPOINT_NATIVE_BASE_URI"]; // ADFS using fed auth string sharePointStsTokenUri = Configuration["SHAREPOINT_STS_TOKEN_URI"]; // Full URI to the STS service we will use to get the initial token. string sharePointRelyingPartyIdentifier = Configuration["SHAREPOINT_RELYING_PARTY_IDENTIFIER"]; // use Fiddler to grab this from an interactive session. Will normally start with urn: string sharePointUsername = Configuration["SHAREPOINT_USERNAME"]; // Service account username. Be sure to add this user to the SharePoint instance. string sharePointPassword = Configuration["SHAREPOINT_PASSWORD"]; // Service account password // SharePoint Online string sharePointAadTenantId = Configuration["SHAREPOINT_AAD_TENANTID"]; string sharePointClientId = Configuration["SHAREPOINT_CLIENT_ID"]; string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"]; string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"]; // Basic Auth (SSG API Gateway) string ssgUsername = Configuration["SSG_USERNAME"]; // BASIC authentication username string ssgPassword = Configuration["SSG_PASSWORD"]; // BASIC authentication password // sometimes SharePoint could be using a different username / password. string sharePointSsgUsername = Configuration["SHAREPOINT_SSG_USERNAME"]; string sharePointSsgPassword = Configuration["SHAREPOINT_SSG_PASSWORD"]; if (string.IsNullOrEmpty(sharePointSsgUsername)) { sharePointSsgUsername = ssgUsername; } if (string.IsNullOrEmpty(sharePointSsgPassword)) { sharePointSsgPassword = ssgPassword; } OdataUri = sharePointOdataUri; ServerAppIdUri = sharePointServerAppIdUri; NativeBaseUri = sharePointNativeBaseURI; WebName = sharePointWebname; // ensure the webname has a slash. if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/') { WebName = "/" + WebName; } ApiEndpoint = sharePointOdataUri; // ensure there is a trailing slash. if (!ApiEndpoint.EndsWith("/")) { ApiEndpoint += "/"; } ApiEndpoint += "_api/"; // Scenario #1 - ADFS (2016) using FedAuth if (!string.IsNullOrEmpty(sharePointRelyingPartyIdentifier) && !string.IsNullOrEmpty(sharePointUsername) && !string.IsNullOrEmpty(sharePointPassword) && !string.IsNullOrEmpty(sharePointStsTokenUri) ) { Authorization = null; var samlST = Authentication.GetStsSamlToken(sharePointRelyingPartyIdentifier, sharePointUsername, sharePointPassword, sharePointStsTokenUri).GetAwaiter().GetResult(); //FedAuthValue = Authentication.GetFedAuth(sharePointOdataUri, samlST, sharePointRelyingPartyIdentifier, _Client, _CookieContainer).GetAwaiter().GetResult(); } // Scenario #2 - SharePoint Online (Cloud) using a Client Certificate else if (!string.IsNullOrEmpty(sharePointAadTenantId) && !string.IsNullOrEmpty(sharePointCertFileName) && !string.IsNullOrEmpty(sharePointCertPassword) && !string.IsNullOrEmpty(sharePointClientId) ) { // add authentication. var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + sharePointAadTenantId); // Create the Client cert. X509Certificate2 cert = new X509Certificate2(sharePointCertFileName, sharePointCertPassword); ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(sharePointClientId, cert); //ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(sharePointServerAppIdUri, clientAssertionCertificate); task.Wait(); authenticationResult = task.Result; Authorization = authenticationResult.CreateAuthorizationHeader(); } else // Scenario #3 - Using an API Gateway with Basic Authentication. The API Gateway will handle other authentication and have different credentials, which may be NTLM { // authenticate using the SSG. string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(sharePointSsgUsername + ":" + sharePointSsgPassword)); Authorization = "Basic " + credentials; } // Authorization header is used for Cloud or Basic API Gateway access if (!string.IsNullOrEmpty(Authorization)) { _Client.DefaultRequestHeaders.Add("Authorization", Authorization); } // Add a Digest header. Needed for certain API operations Digest = GetDigest(_Client).GetAwaiter().GetResult(); if (Digest != null) { _Client.DefaultRequestHeaders.Add("X-RequestDigest", Digest); } // Standard headers for API access _Client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); _Client.DefaultRequestHeaders.Add("OData-Version", "4.0"); }
// Gets an access token. First tries to get the access token from the token cache. // This app uses a password (secret) to authenticate. Production apps should use a certificate. //public async Task<string> GetAppAccessTokenAsync() //{ // try // { // // For development mode purposes only. Production apps should use a client certificate. // return await GetUserAccessTokenAsync(_tenantId); // } // catch (AdalException ex) // { // throw ex; // } //} // TODO: Once the new method above has been fully tested, deprecate the cmmented code below: // Gets an access token. First tries to get the access token from the token cache. // This app uses a password (secret) to authenticate. Production apps should use a certificate. public async Task <string> GetAppAccessTokenAsync() { AuthenticationContext authContext = new AuthenticationContext($"{ _aadInstance }{ _tenantId }", null); try { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult = await authContext.AcquireTokenAsync( _graphResourceId, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_appId, _appSecret)); // For development mode purposes only. Production apps should use a client certificate. return(authResult.AccessToken); } catch (AdalException ex) { throw ex; } }
private async Task <AuthenticationResult> AcquireTokenAsync(bool forceRefresh = false) { bool acquired = false; if (forceRefresh) { authContext.TokenCache.Clear(); } try { // The ADAL client team recommends limiting concurrency of calls. When the Token is in cache there is never // contention on this semaphore, but when tokens expire there is some. However, after measuring performance // with and without the semaphore (and different configs for the semaphore), not limiting concurrency actually // results in higher response times overall. Without the use of this semaphore calls to AcquireTokenAsync can take up // to 5 seconds under high concurrency scenarios. acquired = tokenRefreshSemaphore.Wait(SemaphoreTimeout); // If we are allowed to enter the semaphore, acquire the token. if (acquired) { // Acquire token async using MSAL.NET // https://github.com/AzureAD/azure-activedirectory-library-for-dotnet // Given that this is a ClientCredential scenario, it will use the cache without the // need to call AcquireTokenSilentAsync (which is only for user credentials). // Scenario details: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Client-credential-flows#it-uses-the-application-token-cache AuthenticationResult authResult = null; // Password based auth if (clientCredential != null) { authResult = await authContext.AcquireTokenAsync(authConfig.Scope, this.clientCredential).ConfigureAwait(false); } // Certificate based auth else if (clientCertificate != null) { authResult = await authContext.AcquireTokenAsync(authConfig.Scope, clientCertificate).ConfigureAwait(false); } // This means we acquired a valid token successfully. We can make our retry policy null. // Note that the retry policy is set under the semaphore so no additional synchronization is needed. if (currentRetryPolicy != null) { currentRetryPolicy = null; } return(authResult); } else { // If the token is taken, it means that one thread is trying to acquire a token from the server. // If we already received information about how much to throttle, it will be in the currentRetryPolicy. // Use that to inform our next delay before trying. throw new ThrottleException() { RetryParams = currentRetryPolicy }; } } catch (Exception ex) { // If we are getting throttled, we set the retry policy according to the RetryAfter headers // that we receive from the auth server. // Note that the retry policy is set under the semaphore so no additional synchronization is needed. if (IsAdalServiceUnavailable(ex)) { currentRetryPolicy = ComputeAdalRetry(ex); } throw; } finally { // Always release the semaphore if we acquired it. if (acquired) { ReleaseSemaphore(); } } }
public static IDataFactoryManagementClient GetRealClient(ExampleSecrets secrets) { IDataFactoryManagementClient client = null; if (secrets.Environment == "test") { string ArmTenant = secrets.TenantId; string ArmServicePrincipalIdentity = secrets.ClientId; string SubId = secrets.SubId; string Thumb = secrets.ClientSecret; // Use service principal with cert to authenticate against Azure X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindByThumbprint, Thumb, false)[0]; ClientAssertionCertificate cac = new ClientAssertionCertificate(ArmServicePrincipalIdentity, cert); var context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant); AuthenticationResult result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new DataFactoryManagementClient(creds) { SubscriptionId = SubId }; client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/"); } else if (secrets.Environment == "dogfood") { string ArmTenant = secrets.TenantId; string ArmServicePrincipalIdentity = secrets.ClientId; string SubId = secrets.SubId; // Use service principal with key to authenticate against Azure string secret = secrets.ClientSecret; var cac = new ClientCredential(ArmServicePrincipalIdentity, secret); var context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant); AuthenticationResult result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new DataFactoryManagementClient(creds) { SubscriptionId = SubId }; client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/"); } else if (secrets.Environment == "prod") { // Use Service Principal to authenticate against Azure var context = new AuthenticationContext("https://login.windows.net/" + secrets.TenantId); ClientCredential cc = new ClientCredential(secrets.ClientId, secrets.ClientSecret); AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new DataFactoryManagementClient(creds) { SubscriptionId = secrets.SubId }; } else if (secrets.Environment == "nightly") { // Use certificate for direct access to RP X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindByThumbprint, "CF6DCEF6F6EB497A1B2A569319D157F875019A9E", false)[0]; CertificateCredentials creds = new CertificateCredentials(cert); client = new DataFactoryManagementClient(creds) { SubscriptionId = secrets.SubId }; client.BaseUri = new Uri("https://adfrpnightly.svc.datafactory-test.azure.com"); } else { throw new ArgumentException("Secrets environment must be test or prod, currently {0}", secrets.Environment); } return(client); }
public static async Task <string> AcquireTokenAsync(Dictionary <string, string> input) { Dictionary <string, object> res = new Dictionary <string, object>(); AuthenticationContext ctx = new AuthenticationContext(input["authority"]); try { AuthenticationResult result = null; if (!input.ContainsKey("redirect_uri")) { UserCredential userCred = new UserCredential(); result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], userCred).ConfigureAwait(false); } else if (input.ContainsKey("user_identifier") && input.ContainsKey("password")) { UserPasswordCredential user = new UserPasswordCredential(input["user_identifier"], input["password"]); result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], user).ConfigureAwait(false); } else if (input.ContainsKey("user_identifier") && input.ContainsKey("user_identifier_type")) { // user identifier type defaults to RequiredDisplayableId UserIdentifierType userIdentifierType = UserIdentifierType.RequiredDisplayableId; if (string.Equals(input["user_identifier_type"], "unique_id", StringComparison.InvariantCultureIgnoreCase)) { userIdentifierType = UserIdentifierType.UniqueId; } else if (string.Equals(input["user_identifier_type"], "optional_displayable", StringComparison.InvariantCultureIgnoreCase)) { userIdentifierType = UserIdentifierType.OptionalDisplayableId; } else if (string.Equals(input["user_identifier_type"], "required_displayable", StringComparison.InvariantCultureIgnoreCase)) { userIdentifierType = UserIdentifierType.RequiredDisplayableId; } string prompt = input.ContainsKey("prompt_behavior") ? input["prompt_behavior"] : null; if (input.ContainsKey("claims")) { result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]), GetPlatformParametersInstance(prompt), new UserIdentifier(input["user_identifier"], userIdentifierType), null, input["claims"]) .ConfigureAwait(false); } else { result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]), GetPlatformParametersInstance(prompt), new UserIdentifier(input["user_identifier"], userIdentifierType)) .ConfigureAwait(false); } } else { string prompt = input.ContainsKey("prompt_behavior") ? input["prompt_behavior"] : null; result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]), GetPlatformParametersInstance(prompt)).ConfigureAwait(false); } res = ProcessResult(result, input); } catch (Exception exc) { res.Add("error", exc.Message); } return(FromDictionaryToJson(res)); }
public static Rm.IResourceManagementClient GetRealRmClient(ExampleSecrets secrets) { Rm.IResourceManagementClient client = null; if (secrets.Environment == "test") { string ArmTenant = secrets.TenantId; string ArmServicePrincipalIdentity = secrets.ClientId; string SubId = secrets.SubId; string Thumb = secrets.ClientSecret; // Use service principal with cert to authenticate against Azure X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindByThumbprint, Thumb, false)[0]; ClientAssertionCertificate cac = new ClientAssertionCertificate(ArmServicePrincipalIdentity, cert); var context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant); AuthenticationResult result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new Rm.ResourceManagementClient(creds) { SubscriptionId = secrets.SubId }; client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/"); } else if (secrets.Environment == "dogfood") { string ArmTenant = secrets.TenantId; string ArmServicePrincipalIdentity = secrets.ClientId; string SubId = secrets.SubId; // Use service principal with cert to authenticate against Azure string secret = secrets.ClientSecret; var cac = new ClientCredential(ArmServicePrincipalIdentity, secret); var context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant); AuthenticationResult result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new Rm.ResourceManagementClient(creds) { SubscriptionId = secrets.SubId }; client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/"); } else if (secrets.Environment == "prod") { // Use Service Principal to authenticate against Azure var context = new AuthenticationContext("https://login.windows.net/" + secrets.TenantId); ClientCredential cc = new ClientCredential(secrets.ClientId, secrets.ClientSecret); AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result; ServiceClientCredentials creds = new TokenCredentials(result.AccessToken); client = new Rm.ResourceManagementClient(creds) { SubscriptionId = secrets.SubId }; } else if (secrets.Environment == "nightly") { return(null); // Nightly environment is direct access to our RP, so no ARM } else { throw new ArgumentException("Secrets environment must be test, prod, or nightly, currently {0}", secrets.Environment); } return(client); }
public async Task <ActionResult> Index(string projectname, string participantname, string submitbutton) { if (ModelState.IsValid) { // // Retrieve the user's tenantID and access token since // they are parameters used to call the To Do service. // AuthenticationResult result = null; List <ComputationInfoParticipant> projectParticipantsList = new List <ComputationInfoParticipant>(); try { string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.CentralRegistryAuthority, new NaiveSessionCache(userObjectID, HttpContext.Session)); ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret); result = await authContext.AcquireTokenAsync(AzureAdOptions.Settings.CentralRegistryResourceAppId, credential); // Forms encode participant record, to POST to the MRSDistComp Web API. HttpContent content = new StringContent(JsonConvert.SerializeObject(new { projectname = projectname, participantname = participantname, operation = submitbutton }), System.Text.Encoding.UTF8, "application/json"); // // Add new project participant. // HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.CentralRegistryBaseAddress + "/api/EnrollInProject"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); // // Return the To Do List in the view. // if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else { // // If the call failed with access denied, then drop the current access token from the cache, // and show the user an error indicating they might need to sign-in again. // if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { var cachedTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.CentralRegistryResourceAppId); foreach (TokenCacheItem tci in cachedTokens) { authContext.TokenCache.DeleteItem(tci); } // // The user needs to re-authorize. Show them a message to that effect. // ComputationInfoParticipant newProjectParticipant = new ComputationInfoParticipant(); newProjectParticipant.Id = "(Sign-in required to view project participants.)"; projectParticipantsList.Add(newProjectParticipant); ViewBag.ErrorMessage = "UnexpectedError"; return(View(projectParticipantsList)); } } } catch { // // The user needs to re-authorize. Show them a message to that effect. // // // The user needs to re-authorize. Show them a message to that effect. // ComputationInfoParticipant newProjectParticipant = new ComputationInfoParticipant(); newProjectParticipant.Id = "(Sign-in required to view project participants.)"; projectParticipantsList.Add(newProjectParticipant); ViewBag.ErrorMessage = "AuthorizationRequired"; return(View(projectParticipantsList)); } // // If the call failed for any other reason, show the user an error. // return(View("Error")); } return(View("Error")); }
// register application as native. public async Task <ActionResult> TestReport(string username, string roles) { string GroupId = "me"; string ReportId = "0400c967-973f-43ad-9959-1868e548e0ac"; var result = new EmbededConfig(); try { result = new EmbededConfig { Username = username, Roles = roles }; var error = GetWebConfigErrors(); if (error != null) { result.ErrorMessage = error; return(View(result)); } var credential = new UserPasswordCredential(Username, Password); var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential); if (authenticationResult == null) { result.ErrorMessage = "Authentication Failed."; return(View(result)); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { var reports = await client.Reports.GetReportsInGroupAsync(GroupId); Report report; if (string.IsNullOrEmpty(ReportId)) { report = reports.Value.FirstOrDefault(); } else { report = reports.Value.FirstOrDefault(r => r.Id == ReportId); } if (report == null) { result.ErrorMessage = "Group has no reports."; return(View(result)); } var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(GroupId, report.DatasetId); result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired; result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired; GenerateTokenRequest generateTokenRequestParameters; if (!string.IsNullOrEmpty(username)) { var rls = new EffectiveIdentity(username, new List <string> { report.DatasetId }); if (!string.IsNullOrWhiteSpace(roles)) { var rolesList = new List <string>(); rolesList.AddRange(roles.Split(',')); rls.Roles = rolesList; } generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> { rls }); } else { generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); } var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { result.ErrorMessage = "Failed to generate embed token."; return(View(result)); } result.EmbedToken = tokenResponse; result.EmbedUrl = report.EmbedUrl; result.Id = report.Id; return(View(result)); } } catch (HttpOperationException exc) { result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault()); } catch (Exception exc) { result.ErrorMessage = exc.ToString(); } return(View(result)); }
public async Task <ActionResult> EmbedTile() { var error = GetWebConfigErrors(); if (error != null) { return(View(new TileEmbedConfig() { ErrorMessage = error })); } // Create a user password cradentials. var credential = new UserPasswordCredential(Username, Password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential); if (authenticationResult == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Authentication Failed." })); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { // Get a list of dashboards. var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId); // Get the first report in the group. var dashboard = dashboards.Value.FirstOrDefault(); if (dashboard == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Group has no dashboards." })); } var tiles = await client.Dashboards.GetTilesInGroupAsync(GroupId, dashboard.Id); // Get the first tile in the group. var tile = tiles.Value.FirstOrDefault(); // Generate Embed Token for a tile. var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); var tokenResponse = await client.Tiles.GenerateTokenInGroupAsync(GroupId, dashboard.Id, tile.Id, generateTokenRequestParameters); if (tokenResponse == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Failed to generate embed token." })); } // Generate Embed Configuration. var embedConfig = new TileEmbedConfig() { EmbedToken = tokenResponse, EmbedUrl = tile.EmbedUrl, Id = tile.Id, dashboardId = dashboard.Id }; return(View(embedConfig)); } }
/// <summary> /// Checks that an access token is available. /// </summary> /// <returns>The access token.</returns> internal static async Task <string> EnsureAccessTokenAvailableAsync(string serviceResourceId) { try { // First, look for the authority used during the last authentication. // If that value is not populated, use _commonAuthority. string authority = null; if (String.IsNullOrEmpty(_lastAuthority)) { authority = _commonAuthority; } else { authority = _lastAuthority; } // Create an AuthenticationContext using this authority. _authenticationContext = new AuthenticationContext(authority); // Set the value of _authenticationContext.UseCorporateNetwork to true so that you // can use this app inside a corporate intranet. If the value of UseCorporateNetwork // is true, you also need to add the Enterprise Authentication, Private Networks, and // Shared User Certificates capabilities in the Package.appxmanifest file. //_authenticationContext.UseCorporateNetwork = true; //Get the current app object, which exposes the ClientId and ReturnUri properties // that we need in the following call to AcquireTokenAsync App currentApp = (App)App.Current; AuthenticationResult authenticationResult; // An attempt is first made to acquire the token silently. // If that fails, then we try to acquire the token by prompting the user. authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(serviceResourceId, currentApp.ClientId); if (authenticationResult.Status != AuthenticationStatus.Success) { // Try to authenticate by prompting the user authenticationResult = await _authenticationContext.AcquireTokenAsync(serviceResourceId, currentApp.ClientId, currentApp.ReturnUri); // Check the result of the authentication operation if (authenticationResult.Status != AuthenticationStatus.Success) { // Something went wrong, probably the user cancelled the sign in process return(null); } } // Store relevant info about user and resource _loggedInUser = authenticationResult.UserInfo.UniqueId; // The new last authority is in the form https://login.windows.net/{TenantId} _lastAuthority = App.Current.Resources["ida:AuthorizationUri"].ToString() + authenticationResult.TenantId; UserAccount = authenticationResult.UserInfo.DisplayableId; ServiceResourceId = serviceResourceId; // If the acccess token has changed if (!String.Equals(_accessToken, authenticationResult.AccessToken)) { // Raise an event to let other components know that the token has changed, // so they can react accordingly (for example, updating the data source) AccessTokenChanged(null, EventArgs.Empty); // and store the new acces token _accessToken = authenticationResult.AccessToken; } return(_accessToken); } // The following is a list of all exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. _authenticationContext.TokenCache.Clear(); return(null); } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user _authenticationContext.TokenCache.Clear(); return(null); } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception _authenticationContext.TokenCache.Clear(); return(null); } }
private Task<AuthenticationResult> GetAuthAsync() { var tcs = new TaskCompletionSource<AuthenticationResult>(); AuthenticationResult res = null; Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/common"); try { // Idea here is to always call AcquireToken and it will deal with caching and refresh, etc.. res = await ac.AcquireTokenAsync(Resource, ClientId, redirectUri); tcs.SetResult(res); } catch (Exception ex) { tcs.SetException(ex); } }); return tcs.Task; }
protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null) { var tcs = new TaskCompletionSource <TokenCacheInfo>(); resource = resource ?? Constants.CSMResources[(int)AzureEnvironments]; TokenCacheInfo found; if (tokenCache.TryGetValue(tenantId, resource, out found)) { tcs.SetResult(found); return(tcs.Task); } var thread = new Thread(async() => { try { var azureEnvironment = this.AzureEnvironments; var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId); var context = new AuthenticationContext( authority: authority, validateAuthority: true, tokenCache: tokenCache); AuthenticationResult result = null; if (!string.IsNullOrEmpty(user)) { try { #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Never), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif } catch (AdalException adalEx) { if (adalEx.Message.IndexOf("user_interaction_required") < 0) { throw; } #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Auto), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(), userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId)); #endif } } else { #if NET471 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters(PromptBehavior.Always)); #endif #if NETCOREAPP2_0 result = await context.AcquireTokenAsync( resource: resource, clientId: Constants.AADClientId, redirectUri: new Uri(Constants.AADRedirectUri), parameters: new PlatformParameters()); #endif } var cacheInfo = new TokenCacheInfo(resource, result); tokenCache.Add(cacheInfo); tcs.TrySetResult(cacheInfo); } catch (Exception ex) { tcs.TrySetException(ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Name = "AcquireTokenThread"; thread.Start(); return(tcs.Task); }