public IActionResult ClaimsUser() { using (SAEONLogs.MethodCall(GetType())) { try { var result = HttpContext.UserInfo(); SAEONLogs.Information("UserInfo: {@UserInfo}", result); return(new JsonResult(result, new JsonSerializerOptions { WriteIndented = true })); } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
public AzureCosmosDB(string databaseId, string containerId, string partitionKey, bool allowBulkExecution = false) { using (SAEONLogs.MethodCall <T>(GetType())) { try { var cosmosDBUrl = ConfigurationManager.AppSettings["AzureCosmosDBUrl"]; if (string.IsNullOrWhiteSpace(cosmosDBUrl)) { throw new ArgumentNullException("AppSettings.AzureCosmosDBUrl cannot be null"); } var authKey = ConfigurationManager.AppSettings["AzureCosmosDBAuthKey"]; if (string.IsNullOrWhiteSpace(authKey)) { throw new ArgumentNullException("AppSettings.AzureCosmosDBAuthKey cannot be null"); } var clientOptions = new CosmosClientOptions { AllowBulkExecution = allowBulkExecution, MaxRetryAttemptsOnRateLimitedRequests = int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBRetries"] ?? DefaultRetries.ToString()), MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBRetryWaitSecs"] ?? DefaultRetryWaitSecs.ToString())) }; client = new CosmosClient(cosmosDBUrl, authKey, clientOptions); DatabaseId = databaseId; ContainerId = containerId; PartitionKey = partitionKey; Throughput = int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBThroughput"] ?? DefaultThroughput.ToString()); SAEONLogs.Information("CosmosDbUrl: {CosmosDbUrl} Database: {DatabaseId} Container: {ContainerId} PartitionKey: {PartitionKey} Throughput: {Throughput} BulkExecution: {BulkExection}", cosmosDBUrl, DatabaseId, ContainerId, PartitionKey, Throughput, allowBulkExecution); } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { using (SAEONLogs.MethodCall(GetType())) { try { //SAEONLogs.Information("ContentRoot: {contentRoot} WebRoot: {webRoot}", env.ContentRootPath, env.WebRootPath); SAEONLogs.Information("Development: {IsDevelopment}", env.IsDevelopment()); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpsRedirection(); app.UseResponseCompression(); app.UseResponseCaching(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = $"public,max-age={Defaults.CacheDuration}"; } }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")), RequestPath = "/node_modules", }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Archive")), RequestPath = "/Archive", OnPrepareResponse = ctx => { ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = $"public,max-age={Defaults.CacheDuration}"; } }); var supportedCultures = new[] { new CultureInfo("en-GB") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-GB"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); app.UseRouting(); app.UseCookiePolicy(); app.UseCors("SAEIS"); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health"); endpoints.MapDefaultControllerRoute(); //endpoints.MapControllerRoute( // name: "default", // pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { using (SAEONLogs.MethodCall(GetType())) { try { SAEONLogs.Information("Configuring services"); services.AddApplicationInsightsTelemetry(); services.AddMemoryCache(); services.Configure <CookiePolicyOptions>(options => { //SAEONLogs.Verbose("Options 1: {@Options}", options); //options.CheckConsentNeeded = context => true; options.Secure = CookieSecurePolicy.Always; options.HttpOnly = HttpOnlyPolicy.Always; options.MinimumSameSitePolicy = SameSiteMode.None; //options.MinimumSameSitePolicy = SameSiteMode.Unspecified; //SAEONLogs.Verbose("Options 2: {@Options}", options); }); //services.AddCors(options => options.AddPolicy("SAEIS", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddCors(options => options.AddPolicy("SAEIS", p => p.WithOrigins("https://*****:*****@Options}", options); }); services.AddAuthorization(); services.AddControllers(); services.AddControllersWithViews(); services.AddRazorPages(); IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); services.AddSingleton <IFileProvider>(physicalProvider); } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { using (SAEONLogs.MethodCall(GetType())) { try { SAEONLogs.Debug("IntrospectionUrl: {IntrospectionUrl}", Options.IntrospectionUrl); var token = Request.GetBearerToken(); if (string.IsNullOrWhiteSpace(token)) { SAEONLogs.Error("ODPAuthorization Failed, no token"); return(AuthenticateResult.Fail("No token")); } SAEONLogs.Debug("Token: {Token}", token); // Validate token using (var client = new HttpClient()) { client.SetBearerToken(token); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); using (var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("token", token) })) { var response = await client.PostAsync(new Uri(Options.IntrospectionUrl), formContent).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { SAEONLogs.Error("HttpError: {StatusCode} {Reason}", response.StatusCode, response.ReasonPhrase); SAEONLogs.Error("Response: {Response}", await response.Content.ReadAsStringAsync().ConfigureAwait(false)); } response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false); SAEONLogs.Information("Response: {Response}", json); var jObj = JObject.Parse(json); var isActive = jObj.Value <bool>("active"); if (!isActive) { SAEONLogs.Error("ODPAuthorization, invalid token {Token}", token); return(AuthenticateResult.Fail("Invalid token")); } if (jObj["ext"] is null) { // Access token var clientId = jObj.Value <string>("client_id"); var claims = new List <Claim> { new Claim(ODPAuthenticationDefaults.ClientIdClaim, clientId), new Claim(ODPAuthenticationDefaults.AccessTokenClaim, token) }; var identity = new ClaimsIdentity(claims, ODPAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, ODPAuthenticationDefaults.AuthenticationScheme); SAEONLogs.Debug("ODPAuthentication access token succeeded Claims: {@Claims}", claims.ToClaimsList()); return(AuthenticateResult.Success(ticket)); } else { var clientId = jObj.Value <string>("client_id"); var userId = jObj["ext"].Value <string>("user_id"); var userEmail = jObj["ext"].Value <string>("email"); var userRoles = from r in jObj["ext"]["access_rights"] select(string) r["role_name"]; SAEONLogs.Debug("User Id: {Id} Email: {Email}, Roles: {Role}", userId, userEmail, userRoles); var claims = new List <Claim> { new Claim(ODPAuthenticationDefaults.ClientIdClaim, clientId), new Claim(ODPAuthenticationDefaults.IdTokenClaim, token), new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Email, userId) }; foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); } if (userRoles.Contains("admin") || userRoles.Contains("Admin")) { claims.Add(new Claim(ODPAuthenticationDefaults.AdminTokenClaim, true.ToString())); } var identity = new ClaimsIdentity(claims, ODPAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, ODPAuthenticationDefaults.AuthenticationScheme); SAEONLogs.Debug("ODPAuthentication id token succeeded Claims: {@Claims}", claims.ToClaimsList()); return(AuthenticateResult.Success(ticket)); } } } } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }