public void ConfigureServices(IServiceCollection services) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddHttpClient(); services.AddHttpClient("protectedapi", options => { options.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }); services.AddSingleton <ILoggerManager, LoggerManager>(); services.AddSingleton <IAccessTokenService, AccessTokenService>(); services.AddScoped <IProtectedWebApiCallerService, ProtectedWebApiCallerService>(); services.AddTransient <IResourceFetchService, ResourceFetchService>(); services.AddTransient <IPatientService, PatientService>(); services.AddTransient <IObservationService, ObservationService>(); services.AddTransient <IAggregateService, AggregateService>(); services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); }
private async Task <AuthenticationResult> CreateAccessToken() { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); string[] scopes = new string[] { config.Scope }; AuthenticationResult result = null; try { _logger.LogInfo("Class: AccessTokenService, Method: CreateAccessToken, Info: Acquire Token For Client."); result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); } catch (MsalUiRequiredException ex) { _logger.LogError($"Class: AccessTokenService, Method: CreateAccessToken, {Environment.NewLine} Exception: {ex}, {Environment.NewLine} Message: {ex.Message}, {Environment.NewLine} StackTrace: {ex.StackTrace}"); return(result); } catch (MsalServiceException ex) { _logger.LogError($"Class: AccessTokenService, Method: CreateAccessToken, {Environment.NewLine} Exception: {ex}, {Environment.NewLine} Message: {ex.Message}, {Environment.NewLine} StackTrace: {ex.StackTrace}"); return(result); } return(result); }
public async Task <AuthenticationResult> GetGraphAuthResult() { if (this._authResult != null) { return(this._authResult); } Task <AuthenticationResult> result = null; lock (this) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; if (isUsingClientSecret) { app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); } else { X509Certificate2 certificate = ReadCertificate(config.CertificateName); app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithCertificate(certificate) .WithAuthority(new Uri(config.Authority)) .Build(); } // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator. string[] scopes = new string[] { $"{config.ApiUrl}.default" }; try { result = app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } } return(await result); }
public static async Task <List <Models.MeetingView> > GetUserEventsByEmailSQL(string email) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); using (var db = new Models.NibrContext()) { //return await db.St2hMeetingViews.FromSqlInterpolated($"SELECT * FROM dbo.st2h_meeting_view").Where(b => b.Email == email && b.StartTime < dtDateTill).ToListAsync<Models.St2hMeetingView>(); return(await db.MeetingViews.FromSqlInterpolated($"SELECT Distinct [Start Time] ,[End Time] ,[Channel] ,[Description] ,[Event URL],Email ,SiteId FROM [dbo].[meeting_view]").Where(o => o.SiteId == config.SiteID && o.Email == email).OrderBy(o => o.StartTime).ToListAsync <Models.MeetingView>()); } }
public MsTeamsChannelProvider() { _authConfig = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // NOTE: For testing purposes on my machine #if DEBUG if (Environment.MachineName == "PC") { _authConfig = AuthenticationConfig.ReadFromJsonFile("appsettings-dk-machine.json"); } #endif }
public async Task <ActionResult <JObject> > Get(string groupid) { if (string.IsNullOrEmpty(groupid)) { return(new JObject { "You must include a group id" }); } AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator string[] scopes = new string[] { "https://graph.microsoft.com/.default" }; JObject returnValue = new JObject(); AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } if (result != null) { var httpClient = new HttpClient(); var apiCaller = new ProtectedApiCallHelper(httpClient); // await apiCaller.CallWebApiAndProcessResultASync($"https://graph.microsoft.com/v1.0/groups/{groupid}", result.AccessToken, Display); returnValue = await apiCaller.CallWebApiASync($"https://graph.microsoft.com/v1.0/groups/{groupid}", result.AccessToken); } return(returnValue); }
public static async Task <JsonResult> PostYammer(string msg, IFormFile formFile) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); var httpClient = new HttpClient(); var apiCaller = new APIHelper(httpClient); var getUrl = config.YammerPostGroupMessages;// string.Format(config.YammerGetGroupMessages, config.YammerGroupID); var response = await apiCaller.CallYammerPostResultASync(getUrl, config.YammerUploadGroupID, config.YammerTocken, Display, msg, formFile); return(response); // await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display); }
private static async Task RunAsync() { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator string[] scopes = new string[] { config.TodoListScope }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired \n"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } if (result != null) { var httpClient = new HttpClient(); var apiCaller = new ProtectedApiCallHelper(httpClient); await apiCaller.CallWebApiAndProcessResultASync($"{config.TodoListBaseAddress}/api/todolist/all", result.AccessToken, Display); } }
private Stream GetStreamForOneDrive() { var config = AuthenticationConfig.ReadFromJsonFile("graphsettings.json"); config.CheckParameters(); _graphServiceClient = GraphClientFactory.GraphClientFactory.GetGraphServiceClient ( config.ClientId, config.Authority, config.RedirectUri, config.Scopes ); var request = _graphServiceClient.Me.Drive.Root.ItemWithPath(_fileName).Content .Request() .GetAsync(); return(request .GetAwaiter() .GetResult()); }
private static async Task RunAsync() { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile(@"appsettings.json"); IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); string[] scopes = new string[] { $"{config.ApiUrl}.default" }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes).ExecuteAsync(); } catch (MsalUiRequiredException ex) { Console.WriteLine($"Insufficient permissions {ex.Message}"); return; } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { Console.WriteLine($"Invalid scope: {ex.Message}"); return; } catch (Exception ex) { Console.WriteLine(ex.Message); return; } var vv = new AuthenticationHeaderValue("Bearer", result.AccessToken); DelegateAuthenticationProvider ds = new DelegateAuthenticationProvider(async(res) => { res.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); }); GraphServiceClient _graphClient = new GraphServiceClient(ds); // REPORTS - https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/534 - workaround var vreportReq = _graphClient.Reports.GetOneDriveActivityFileCounts("D180").Request().GetHttpRequestMessage(); var repResponse = await _graphClient.HttpProvider.SendAsync(vreportReq); string report = string.Empty; if (repResponse.IsSuccessStatusCode) { report = await repResponse.Content.ReadAsStringAsync(); Console.WriteLine(report); } //OneDrive var v = _graphClient.Users["ushjdhisfi"].Drive.Request().GetAsync(); await v.ContinueWith(usr => { Console.WriteLine(usr.Result.WebUrl); }); //User.Read var users = _graphClient.Users.Request().Select(r => new { r.DisplayName, r.UserPrincipalName, r.AccountEnabled, r.Id, r.Drive }).GetAsync(); // user drive https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0&tabs=http await users.ContinueWith(res => { res.Result.ToList <User>().ForEach(r => { Console.WriteLine($"Display Name: {r.DisplayName} - principal name: {r.UserPrincipalName} - Account enabled ? {r.AccountEnabled}"); _graphClient.Users[r.Id].Drive.Request().GetAsync().ContinueWith(d => { Console.WriteLine(d.Result.WebUrl); }).Wait(); _graphClient.Users[r.Id].Drive.Root.Children.Request().GetAsync().ContinueWith(res => { res.Result.ToList <DriveItem>().ForEach(itm => { Console.WriteLine($"Name: {itm.Name} size: {itm.Size} {itm.File} "); }); }); }); Console.WriteLine("sdfd"); }); if (result != null) { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var apiUri = "https://graph.microsoft.com/v1.0/users"; // Call the web API. HttpResponseMessage response = await httpClient.GetAsync(apiUri); var str = await response.Content.ReadAsStringAsync(); Console.WriteLine(str); apiUri = "https://graph.microsoft.com/v1.0/users/delta?$select=displayName,givenName,surname"; response = await httpClient.GetAsync(apiUri); str = await response.Content.ReadAsStringAsync(); Console.WriteLine(str); } }
public static async Task <JsonResult> GraphApiGetUserEventsByEmailFromSharePointList(string email) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; if (isUsingClientSecret) { app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); } else { X509Certificate2 certificate = ReadCertificate(config.CertificateName); app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithCertificate(certificate) .WithAuthority(new Uri(config.Authority)) .Build(); } // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator. string[] scopes = new string[] { $"{config.ApiUrl}.default" }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } if (result != null) { var httpClient = new HttpClient(); var apiCaller = new APIHelper(httpClient); var endpointWithUser = string.Format(config.UserEventsURL, email); var response = await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/{endpointWithUser}", result.AccessToken, Display); var usereventsObj = JObject.Parse(response.Value.ToString()); // JArray userevents = (JArray)eventsObj["value"]; var userEventsorg = usereventsObj["value"].ToString(); var evetns = await GraphApiGetEventSharePointList(); JArray allEvetns = (JArray)JsonConvert.DeserializeObject(evetns.Value.ToString()); JArray userevents = (JArray)JsonConvert.DeserializeObject(userEventsorg); JArray filteredEvetns = new JArray(); //Get user's evetns foreach (var a in userevents) { int lookupId = (int)a["fields"]["EventIDLookupId"]; foreach (var e1 in allEvetns) { int e1id = (int)e1["fields"]["id"]; if (e1id == lookupId) { filteredEvetns.Add(e1); } } } JArray sorted = new JArray(filteredEvetns.OrderBy(obj => (DateTime)obj["fields"]["StartTime"])); var jo = sorted.ToString(); return(new JsonResult(jo)); // await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display); } return(null); }
public static async Task <JsonResult> GraphApiGetSuperUserFromSharePointList(string email) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; if (isUsingClientSecret) { app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); } else { X509Certificate2 certificate = ReadCertificate(config.CertificateName); app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithCertificate(certificate) .WithAuthority(new Uri(config.Authority)) .Build(); } // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator. string[] scopes = new string[] { $"{config.ApiUrl}.default" }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } if (result != null) { var httpClient = new HttpClient(); var apiCaller = new APIHelper(httpClient); var endpointWithUser = string.Format(config.SuperUsersURL, email); var response = await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/{endpointWithUser}", result.AccessToken, Display); return(response); // await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display); } return(null); }
public async Task <IActionResult> Submit([FromBody] FieldData body) { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; if (isUsingClientSecret) { app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); } else { X509Certificate2 certificate = ReadCertificate(config.CertificateName); app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithCertificate(certificate) .WithAuthority(new Uri(config.Authority)) .Build(); } // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator. string[] scopes = new string[] { $"{config.ApiUrl}.default" }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected return(BadRequest("Scope not supported")); } if (result != null) { var SOBListLocation = $"{config.CpscSharepoint},c0cefe40-beeb-41a9-b4f5-9960bcfa010b,fbb78c64-1220-42fe-a319-94c493a9a105/lists/6f53c37b-d6ba-46c3-91a9-2e942a984af9/items"; var webapiUrl = $"{config.ApiUrl}v1.0/sites/{SOBListLocation}"; var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, webapiUrl); httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); var httpClient = new HttpClient(); var apiCaller = new ProtectedApiCallHelper(httpClient); var res = await apiCaller.CallWebApiAndProcessResultASync(httpRequestMessage, result.AccessToken); return(Ok(res)); // await apiCaller.AddToSiteList("siteid", "listId", "payload", Display);// } else { return(Ok("result is null")); } }