using LingAdmin.AuthorizationService.Data; using LingAdmin.AuthorizationService.Services; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add Dapr builder.Services.AddControllers().AddDapr(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new() { Title = "LingAdmin Authorization Service", Version = "v1" }); c.AddSecurityDefinition("Bearer", new() { Description = "JWT Authorization header using the Bearer scheme", Name = "Authorization", In = Microsoft.OpenApi.Models.ParameterLocation.Header, Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new() { { new() { Reference = new() { Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty() } }); }); // Register services builder.Services.AddScoped(); builder.Services.AddScoped(); // Configure JWT Authentication var jwtSettings = builder.Configuration.GetSection("JwtSettings"); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtSettings["Issuer"], ValidAudience = jwtSettings["Audience"], IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(jwtSettings["SecretKey"] ?? throw new InvalidOperationException("JWT SecretKey not configured"))) }; }); // Configure CORS builder.Services.AddCors(options => { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // Add DbContext builder.Services.AddDbContext(options => options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("LingAdmin.AuthorizationService") ) ); // Add memory cache for caching permissions builder.Services.AddMemoryCache(); var app = builder.Build(); // Configure pipeline if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseCors("AllowAll"); app.UseAuthentication(); app.UseAuthorization(); app.UseCloudEvents(); app.MapControllers(); app.MapSubscribeHandler(); // Auto migrate database using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Database.Migrate(); } app.Run();