Program.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Text;
  2. using Database.Database;
  3. using Esim.Apis.Business;
  4. using Microsoft.AspNetCore.Authentication.JwtBearer;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.IdentityModel.Tokens;
  7. var builder = WebApplication.CreateBuilder(args);
  8. // Add services to the container.
  9. builder.Services.AddControllersWithViews();
  10. // Add DbContext
  11. builder.Services.AddDbContext<ModelContext>();
  12. // Add Business Services
  13. builder.Services.AddScoped<IUserBusiness, UserBusinessImpl>();
  14. // Configure JWT Authentication
  15. var jwtKey = builder.Configuration["Jwt:Key"] ?? "EsimLaoSecretKey12345678901234567890";
  16. var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "EsimLao";
  17. var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "EsimLaoClient";
  18. builder.Services.AddAuthentication(options =>
  19. {
  20. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  21. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  22. })
  23. .AddJwtBearer(options =>
  24. {
  25. options.TokenValidationParameters = new TokenValidationParameters
  26. {
  27. ValidateIssuer = true,
  28. ValidateAudience = true,
  29. ValidateLifetime = true,
  30. ValidateIssuerSigningKey = true,
  31. ValidIssuer = jwtIssuer,
  32. ValidAudience = jwtAudience,
  33. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtKey))
  34. };
  35. });
  36. // Add Swagger for API documentation
  37. builder.Services.AddEndpointsApiExplorer();
  38. builder.Services.AddSwaggerGen();
  39. var app = builder.Build();
  40. // Configure the HTTP request pipeline.
  41. if (app.Environment.IsDevelopment())
  42. {
  43. app.UseSwagger();
  44. app.UseSwaggerUI();
  45. }
  46. else
  47. {
  48. app.UseExceptionHandler("/Home/Error");
  49. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  50. app.UseHsts();
  51. }
  52. app.UseHttpsRedirection();
  53. app.UseRouting();
  54. app.UseAuthentication();
  55. app.UseAuthorization();
  56. app.MapStaticAssets();
  57. app.MapControllerRoute(
  58. name: "default",
  59. pattern: "{controller=Home}/{action=Index}/{id?}")
  60. .WithStaticAssets();
  61. app.MapControllers();
  62. app.Run();