DamageAssessment_Backend/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs

151 lines
5.1 KiB
C#
Raw Normal View History

using DamageAssesment.Api.UsersAccess.Db;
using DamageAssesment.Api.UsersAccess.Interfaces;
using DamageAssesment.Api.UsersAccess.Providers;
using DamageAssesment.Api.UsersAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Polly;
using DamageAssesment.Api.UsersAccess.Services;
using Microsoft.OpenApi.Models;
using System.Reflection;
using Microsoft.AspNetCore.Authorization;
const int maxApiCallRetries = 3;
const int intervalToRetry = 2; //2 seconds
const int maxRetryForCircuitBraker = 5;
const int intervalForCircuitBraker = 5; //5 seconds
var builder = WebApplication.CreateBuilder(args);
2023-11-25 23:08:04 -05:00
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
}));
// Add services to the container.
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
builder.Services.AddAuthentication().
AddJwtBearer("DamageApp", item =>
{
item.RequireHttpsMetadata = true;
item.SaveToken = true;
item.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
}).AddJwtBearer("Dadeschools", options =>
{
options.Authority = builder.Configuration["Dadeschools:Authority"];
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
options.TokenValidationParameters.ValidateAudience = false;
});
builder.Services.AddAuthorization(options =>
{
var DamageAppPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("DamageApp")
.Build();
var DadeschoolsPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("Dadeschools")
.Build();
var allPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("DamageApp", "Dadeschools")
.Build();
options.AddPolicy("DamageApp", DamageAppPolicy);
options.AddPolicy("Dadeschools", DadeschoolsPolicy);
options.AddPolicy("AllPolicies", allPolicy);
options.DefaultPolicy = options.GetPolicy("DamageApp")!;
});
var _jwtsettings = builder.Configuration.GetSection("JwtSettings");
builder.Services.Configure<JwtSettings>(_jwtsettings);
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddScoped<IUsersAccessProvider, UsersAccessProvider>();
builder.Services.AddScoped<ITokenServiceProvider, TokenServiceProvider>();
builder.Services.AddScoped<IEmployeeServiceProvider, EmployeeServiceProvider>();
builder.Services.AddHttpClient<IHttpUtil, HttpUtil>().
AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))).
AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker)));
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(options =>
{
// Include XML comments from your assembly
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//options.IncludeXmlComments(xmlPath);
OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
{
Name = "Bearer",
BearerFormat = "JWT",
Scheme = "bearer",
Description = "Specify the authorization token.",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
};
options.AddSecurityDefinition("jwt_auth", securityDefinition);
// Make sure swagger UI requires a Bearer token specified
OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
{
Reference = new OpenApiReference()
{
Id = "jwt_auth",
Type = ReferenceType.SecurityScheme
}
};
OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
{
{securityScheme, new string[] { }},
};
options.AddSecurityRequirement(securityRequirements);
});
builder.Services.AddDbContext<UsersAccessDbContext>(option =>
{
option.UseSqlServer("UsersAccessConnection");
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var usersAccessProvider = services.GetRequiredService<IUsersAccessProvider>();
usersAccessProvider.seedData();
}
}
2023-11-25 23:08:04 -05:00
app.UseCors("DamageAppCorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();