123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Authentication.OAuth;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Migrations;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Options;
- using Microsoft.IdentityModel.Tokens;
- using Microsoft.OpenApi.Any;
- using Microsoft.OpenApi.Models;
- using Npgsql;
- using OnlineMetodist.API.Data;
- using OnlineMetodist.API.Models;
- using OnlineMetodist.API.Services;
- using System.Text;
- using System.Text.Json.Serialization;
- var builder = WebApplication.CreateBuilder(args);
- // Add services to the container.
- builder.Services.AddControllers()
- .AddJsonOptions(options =>
- {
- options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter());
- });
- // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
- builder.Services.AddEndpointsApiExplorer();
- builder.Logging.ClearProviders();
- builder.Logging.AddConsole();
- //íà âðåìÿ ðàçðàáîòêè
- builder.Services.AddProblemDetails();
- //swagger
- builder.Services.AddSwaggerGen(options =>
- {
- options.SwaggerDoc("v1", new OpenApiInfo
- {
- Title = "OnlineMetodist API",
- Version = "v1",
- Description = "ASP.NET Core Web API äëÿ óïðàâëåíèÿ äàíûìè Îíëàéí Ìåòîäèñòà"
- });
- options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
- {
- In = ParameterLocation.Header,
- Description = "Please enter a valid token",
- Name = "Authorization",
- Type = SecuritySchemeType.Http,
- BearerFormat = "JWT",
- Scheme = "Bearer"
- });
- options.AddSecurityRequirement(new OpenApiSecurityRequirement
- {
- {
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type=ReferenceType.SecurityScheme,
- Id="Bearer"
- }
- },
- new List<string>()
- }
- });
- options.MapType<DateOnly>(() => new OpenApiSchema
- {
- Type = "string",
- Format = "date",
- Example = new OpenApiString("2022-01-01")
- });
- });
- //Äîáàâëåíèå ÁÄ
- builder.Services.AddDbContext<OnlineMetodistDbContext>(options =>
- options.UseNpgsql(
- builder.Configuration.GetConnectionString("DefaultConnection")));
- builder.Services.AddScoped<TokenService, TokenService>();
- //builder.Services.AddControllers().AddJsonOptions(opt =>
- //{
- // opt.JsonSerializerOptions.Converters.Add(new JsonConverter<DateOnly>());
- //});
- //Äîáàâëåíèå Identity äëÿ ïîëüçîâàòåëåé
- builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
- {
- options.SignIn.RequireConfirmedAccount = false;
- options.Password.RequiredLength = 6;
- options.Password.RequireDigit = false;
- options.Password.RequireNonAlphanumeric = false;
- options.Password.RequireUppercase = false;
- options.User.RequireUniqueEmail = true;
- })
- .AddRoles<IdentityRole>() //äîáàâëåíè ðîëåé?
- .AddEntityFrameworkStores<OnlineMetodistDbContext>(); //äîáàâëåíèå ÅÔ õðàíèëèùà
- var validIssuer = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidIssuer");
- var validAudience = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidAudience");
- var symmetricSecurityKey = builder.Configuration.GetValue<string>("JwtTokenSettings:SymmetricSecurityKey");
- builder.Services.AddAuthentication(options => {
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
- })
- .AddJwtBearer(options =>
- {
- options.RequireHttpsMetadata = false;
- options.SaveToken = true;
- options.IncludeErrorDetails = true;
- options.TokenValidationParameters = new TokenValidationParameters()
- {
- ClockSkew = TimeSpan.Zero,
- ValidateIssuer = true,
- ValidateAudience = true,
- ValidateLifetime = true,
- ValidateIssuerSigningKey = true,
- ValidIssuer = validIssuer,
- ValidAudience = validAudience,
- IssuerSigningKey = new SymmetricSecurityKey(
- Encoding.UTF8.GetBytes(symmetricSecurityKey)
- ),
- };
- });
- builder.Services.AddAuthorization();
- var app = builder.Build();
- //using (var scope = app.Services.CreateScope())
- //{
- // var services = scope.ServiceProvider;
- // SeedData.Initialize(services);
- //}
- using (var scope = app.Services.CreateScope())
- {
- var services = scope.ServiceProvider;
- try
- {
- var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
- var rolesManager = services.GetRequiredService<RoleManager<IdentityRole>>();
- await SeedData.InitializeAsync(userManager, rolesManager);
- }
- catch (Exception ex)
- {
- var logger = services.GetRequiredService<ILogger<Program>>();
- logger.LogError(ex, "An error occurred while seeding the database.");
- }
- }
- // Configure the HTTP request pipeline.
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(options =>
- {
- //options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
- //options.RoutePrefix = string.Empty;
- options.SwaggerEndpoint("./v1/swagger.json", "v1"); //Îòíîñèòåëüíûé ïóòü äî ïîëüçîâàòåëüñêîãî èíòåðôåéñà
- });
- app.UseHttpsRedirection();
- app.UseStatusCodePages();
- app.UseAuthentication();
- app.UseAuthorization();
- app.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- app.Run();
|