Startup.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. using System.Text;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNetCore.Authentication.JwtBearer;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.IdentityModel.Tokens;
  9. using LAPS_XMLQC_Service.Controllers.Master.User;
  10. using LAPS_XMLQC_Service.Models;
  11. using Microsoft.Extensions.Hosting;
  12. using LAPS_XMLQC_Service.Services;
  13. using LAPS_XMLQC_Service.Controllers.WorkArea;
  14. using LAPS_XMLQC_Service.App_Data;
  15. using Npgsql;
  16. using System.Data;
  17. namespace LAPS_XMLQC_Service
  18. {
  19. public class Startup
  20. {
  21. public Startup(IWebHostEnvironment env)
  22. {
  23. var builder = new ConfigurationBuilder()
  24. .SetBasePath(env.ContentRootPath)
  25. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  26. Configuration = builder.Build();
  27. }
  28. static public IConfigurationRoot Configuration { get; set; }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. public void ConfigureServices(IServiceCollection services)
  31. {
  32. services.AddControllers();
  33. services.AddSwaggerGen();
  34. // Add CORS policy here
  35. services.AddCors(options =>
  36. {
  37. options.AddPolicy("CorsPolicy", builder =>
  38. builder.SetIsOriginAllowed(_ => true)
  39. .AllowAnyMethod()
  40. .AllowAnyHeader()
  41. .AllowCredentials());
  42. });
  43. //services.AddCors(options =>
  44. //{
  45. // options.AddPolicy("CorsPolicy",
  46. // builder => builder.WithOrigins("http://localhost:4200")
  47. // .AllowAnyMethod()
  48. // .AllowAnyHeader()
  49. // .AllowCredentials());
  50. //});
  51. services.AddSingleton<IConfiguration>(Configuration);
  52. // Configure strongly typed settings objects
  53. var appSettingsSection = Configuration.GetSection("AppSettings");
  54. services.Configure<Appsettings>(appSettingsSection);
  55. // Configure JWT authentication
  56. var appSettings = appSettingsSection.Get<Appsettings>();
  57. var key = Encoding.ASCII.GetBytes(appSettings.Secret);
  58. services.AddAuthentication(x =>
  59. {
  60. x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  61. x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  62. })
  63. .AddJwtBearer(x =>
  64. {
  65. x.Events = new JwtBearerEvents
  66. {
  67. OnTokenValidated = context =>
  68. {
  69. var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
  70. var userId = int.Parse(context.Principal.Identity.Name);
  71. var user = userService.GetById(userId);
  72. if (user == null)
  73. {
  74. // Return unauthorized if user no longer exists
  75. context.Fail("Unauthorized");
  76. }
  77. return Task.CompletedTask;
  78. }
  79. };
  80. x.RequireHttpsMetadata = false;
  81. x.SaveToken = true;
  82. x.TokenValidationParameters = new TokenValidationParameters
  83. {
  84. ValidateIssuerSigningKey = true,
  85. IssuerSigningKey = new SymmetricSecurityKey(key),
  86. ValidateIssuer = false,
  87. ValidateAudience = false
  88. };
  89. });
  90. // Register services
  91. services.AddScoped<IUserService, UserService>();
  92. services.AddScoped<IWorkAreaService, WorkAreaService>();
  93. services.AddScoped<FileSearchService>();
  94. services.AddScoped<RegexPatternService>();
  95. services.AddScoped<XmlValidatorService>();
  96. services.AddScoped<CommonRepository>();
  97. services.AddScoped<GrantFolderPermission>();
  98. services.AddScoped<IImpartunateFactory, ImpartunateFactory>();
  99. }
  100. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  101. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  102. {
  103. if (env.IsDevelopment())
  104. {
  105. app.UseDeveloperExceptionPage();
  106. app.UseSwagger();
  107. app.UseSwaggerUI();
  108. }
  109. // This middleware is for handling empty content responses
  110. app.Use(async (ctx, next) =>
  111. {
  112. await next();
  113. if (ctx.Response.StatusCode == 204) // No Content
  114. {
  115. ctx.Response.ContentLength = 0;
  116. }
  117. });
  118. // Enable authentication middleware
  119. app.UseAuthentication();
  120. // Use HTTPS redirection
  121. app.UseHttpsRedirection();
  122. // Enable routing
  123. app.UseRouting();
  124. // Apply CORS policy here
  125. app.UseCors("CorsPolicy");
  126. app.UseCors("AllowAll");
  127. // Enable authorization
  128. app.UseAuthorization();
  129. // Map controllers to the pipeline
  130. app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
  131. }
  132. }
  133. }