using System.Diagnostics; using FrontOffice.BFF.Application.Common.Interfaces; using FrontOffice.BFF.Infrastructure.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Microsoft.Extensions.DependencyInjection; public static class ConfigureServices { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton(); services.AddSingleton(); services.AddInfrastructureGrpcServices(configuration); #region AddAuthentication var message = ""; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwtBearerOptions => { //jwtBearerOptions.Authority = configuration["Authentication:Authority"]; //jwtBearerOptions.Audience = configuration["Authentication:Audience"]; //jwtBearerOptions.TokenValidationParameters.ValidateAudience = false; //jwtBearerOptions.TokenValidationParameters.ValidateIssuer = true; //jwtBearerOptions.TokenValidationParameters.ValidateIssuerSigningKey = false; jwtBearerOptions.SaveToken = true; jwtBearerOptions.RequireHttpsMetadata = false; jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = configuration["JwtIssuer"], ValidAudience = configuration["JwtAudience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSecurityKey"])) }; try { jwtBearerOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = ctx => { ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; message += "From OnAuthenticationFailed:\n"; message += ctx.Exception.Message; return Task.CompletedTask; }, OnChallenge = ctx => { message += "From OnChallenge:\n"; ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; ctx.Response.ContentType = "text/plain"; return ctx.Response.WriteAsync(message); }, OnMessageReceived = ctx => { message = "From OnMessageReceived:\n"; ctx.Request.Headers.TryGetValue("Authorization", out var BearerToken); if (BearerToken.Count == 0) BearerToken = "no Bearer token sent\n"; message += "Authorization Header sent: " + BearerToken + "\n"; return Task.CompletedTask; }, OnTokenValidated = ctx => { Debug.WriteLine("token: " + ctx.SecurityToken.ToString()); return Task.CompletedTask; } }; } catch (Exception e) { Console.WriteLine(e); throw; } }); services.AddAuthorization(); #endregion return services; } }