Program.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using Microsoft.AspNetCore.Authentication.JwtBearer;
  2. using Microsoft.AspNetCore.Authentication.OAuth;
  3. using Microsoft.AspNetCore.Identity;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.EntityFrameworkCore.Migrations;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Options;
  8. using Microsoft.IdentityModel.Tokens;
  9. using Microsoft.OpenApi.Any;
  10. using Microsoft.OpenApi.Models;
  11. using Npgsql;
  12. using OnlineMetodist.API.Data;
  13. using OnlineMetodist.API.Models;
  14. using OnlineMetodist.API.Services;
  15. using System.Text;
  16. using System.Text.Json.Serialization;
  17. var builder = WebApplication.CreateBuilder(args);
  18. // Add services to the container.
  19. builder.Services.AddControllers()
  20. .AddJsonOptions(options =>
  21. {
  22. options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter());
  23. });
  24. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  25. builder.Services.AddEndpointsApiExplorer();
  26. builder.Logging.ClearProviders();
  27. builder.Logging.AddConsole();
  28. //íà âðåìÿ ðàçðàáîòêè
  29. builder.Services.AddProblemDetails();
  30. //swagger
  31. builder.Services.AddSwaggerGen(options =>
  32. {
  33. options.SwaggerDoc("v1", new OpenApiInfo
  34. {
  35. Title = "OnlineMetodist API",
  36. Version = "v1",
  37. Description = "ASP.NET Core Web API äëÿ óïðàâëåíèÿ äàíûìè Îíëàéí Ìåòîäèñòà"
  38. });
  39. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  40. {
  41. In = ParameterLocation.Header,
  42. Description = "Please enter a valid token",
  43. Name = "Authorization",
  44. Type = SecuritySchemeType.Http,
  45. BearerFormat = "JWT",
  46. Scheme = "Bearer"
  47. });
  48. options.AddSecurityRequirement(new OpenApiSecurityRequirement
  49. {
  50. {
  51. new OpenApiSecurityScheme
  52. {
  53. Reference = new OpenApiReference
  54. {
  55. Type=ReferenceType.SecurityScheme,
  56. Id="Bearer"
  57. }
  58. },
  59. new List<string>()
  60. }
  61. });
  62. options.MapType<DateOnly>(() => new OpenApiSchema
  63. {
  64. Type = "string",
  65. Format = "date",
  66. Example = new OpenApiString("2022-01-01")
  67. });
  68. });
  69. //Äîáàâëåíèå ÁÄ
  70. builder.Services.AddDbContext<OnlineMetodistDbContext>(options =>
  71. options.UseNpgsql(
  72. builder.Configuration.GetConnectionString("DefaultConnection")));
  73. builder.Services.AddScoped<TokenService, TokenService>();
  74. //builder.Services.AddControllers().AddJsonOptions(opt =>
  75. //{
  76. // opt.JsonSerializerOptions.Converters.Add(new JsonConverter<DateOnly>());
  77. //});
  78. //Äîáàâëåíèå Identity äëÿ ïîëüçîâàòåëåé
  79. builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
  80. {
  81. options.SignIn.RequireConfirmedAccount = false;
  82. options.Password.RequiredLength = 6;
  83. options.Password.RequireDigit = false;
  84. options.Password.RequireNonAlphanumeric = false;
  85. options.Password.RequireUppercase = false;
  86. options.User.RequireUniqueEmail = true;
  87. })
  88. .AddRoles<IdentityRole>() //äîáàâëåíè ðîëåé?
  89. .AddEntityFrameworkStores<OnlineMetodistDbContext>(); //äîáàâëåíèå ÅÔ õðàíèëèùà
  90. var validIssuer = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidIssuer");
  91. var validAudience = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidAudience");
  92. var symmetricSecurityKey = builder.Configuration.GetValue<string>("JwtTokenSettings:SymmetricSecurityKey");
  93. builder.Services.AddAuthentication(options => {
  94. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  95. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  96. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  97. })
  98. .AddJwtBearer(options =>
  99. {
  100. options.RequireHttpsMetadata = false;
  101. options.SaveToken = true;
  102. options.IncludeErrorDetails = true;
  103. options.TokenValidationParameters = new TokenValidationParameters()
  104. {
  105. ClockSkew = TimeSpan.Zero,
  106. ValidateIssuer = true,
  107. ValidateAudience = true,
  108. ValidateLifetime = true,
  109. ValidateIssuerSigningKey = true,
  110. ValidIssuer = validIssuer,
  111. ValidAudience = validAudience,
  112. IssuerSigningKey = new SymmetricSecurityKey(
  113. Encoding.UTF8.GetBytes(symmetricSecurityKey)
  114. ),
  115. };
  116. });
  117. builder.Services.AddAuthorization();
  118. var app = builder.Build();
  119. //using (var scope = app.Services.CreateScope())
  120. //{
  121. // var services = scope.ServiceProvider;
  122. // SeedData.Initialize(services);
  123. //}
  124. using (var scope = app.Services.CreateScope())
  125. {
  126. var services = scope.ServiceProvider;
  127. try
  128. {
  129. var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
  130. var rolesManager = services.GetRequiredService<RoleManager<IdentityRole>>();
  131. await SeedData.InitializeAsync(userManager, rolesManager);
  132. }
  133. catch (Exception ex)
  134. {
  135. var logger = services.GetRequiredService<ILogger<Program>>();
  136. logger.LogError(ex, "An error occurred while seeding the database.");
  137. }
  138. }
  139. // Configure the HTTP request pipeline.
  140. app.UseDeveloperExceptionPage();
  141. app.UseSwagger();
  142. app.UseSwaggerUI(options =>
  143. {
  144. //options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
  145. //options.RoutePrefix = string.Empty;
  146. options.SwaggerEndpoint("./v1/swagger.json", "v1"); //Îòíîñèòåëüíûé ïóòü äî ïîëüçîâàòåëüñêîãî èíòåðôåéñà
  147. });
  148. app.UseHttpsRedirection();
  149. app.UseStatusCodePages();
  150. app.UseAuthentication();
  151. app.UseAuthorization();
  152. app.MapControllerRoute(
  153. name: "default",
  154. pattern: "{controller=Home}/{action=Index}/{id?}");
  155. app.Run();