Startup.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Authentication.JwtBearer;
  7. using Microsoft.AspNetCore.Builder;
  8. using Microsoft.AspNetCore.Hosting;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.AspNetCore.HttpsPolicy;
  11. // using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.Extensions.Configuration;
  13. using Microsoft.Extensions.DependencyInjection;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.Extensions.Options;
  16. using Microsoft.IdentityModel.Tokens;
  17. using WK_KLI_LAPS_COMMONTOOL_Service.Controllers.Master.User;
  18. using WK_KLI_LAPS_COMMONTOOL_Service.Hub;
  19. using WK_KLI_LAPS_COMMONTOOL_Service.Models;
  20. namespace WK_KLI_LAPS_COMMONTOOL_Service
  21. {
  22. public class Startup
  23. {
  24. public Startup(IHostingEnvironment env)
  25. {
  26. var builder = new ConfigurationBuilder()
  27. .SetBasePath(env.ContentRootPath)
  28. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  29. Configuration = builder.Build();
  30. //Configuration = configuration;
  31. }
  32. static public IConfigurationRoot Configuration { get; set; }
  33. // This method gets called by the runtime. Use this method to add services to the container.
  34. public void ConfigureServices(IServiceCollection services)
  35. {
  36. services.AddCors();
  37. services.AddControllers();
  38. //services.AddCors(options =>
  39. //{
  40. // options.AddPolicy("CorsPolicy",
  41. // builder => builder.AllowAnyOrigin()
  42. // .AllowAnyMethod()
  43. // .AllowAnyHeader()
  44. // .AllowCredentials());
  45. //});
  46. services.AddCors(options =>
  47. {
  48. options.AddPolicy("CorsPolicy", builder =>
  49. builder.SetIsOriginAllowed(_ => true)
  50. .AllowAnyMethod()
  51. .AllowAnyHeader()
  52. .AllowCredentials());
  53. });
  54. services.AddSignalR();
  55. services.AddMvc();
  56. services.AddSingleton<IConfiguration>(Configuration);
  57. // configure strongly typed settings objects
  58. var appSettingsSection = Configuration.GetSection("AppSettings");
  59. services.Configure<Appsettings>(appSettingsSection);
  60. // configure jwt authentication
  61. var appSettings = appSettingsSection.Get<Appsettings>();
  62. //hangfire
  63. //services.AddHangfire(config =>
  64. // config.UsePostgreSqlStorage(appSettings.ConnectionStringSchedule));
  65. var key = Encoding.ASCII.GetBytes(appSettings.Secret);
  66. services.AddAuthentication(x =>
  67. {
  68. x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  69. x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  70. })
  71. .AddJwtBearer(x =>
  72. {
  73. x.Events = new JwtBearerEvents
  74. {
  75. OnTokenValidated = context =>
  76. {
  77. var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
  78. var userId = int.Parse(context.Principal.Identity.Name);
  79. var user = userService.GetById(userId);
  80. if (user == null)
  81. {
  82. // return unauthorized if user no longer exists
  83. context.Fail("Unauthorized");
  84. }
  85. return Task.CompletedTask;
  86. }
  87. };
  88. x.RequireHttpsMetadata = false;
  89. x.SaveToken = true;
  90. x.TokenValidationParameters = new TokenValidationParameters
  91. {
  92. ValidateIssuerSigningKey = true,
  93. IssuerSigningKey = new SymmetricSecurityKey(key),
  94. ValidateIssuer = false,
  95. ValidateAudience = false
  96. };
  97. });
  98. services.AddHttpContextAccessor();
  99. //// configure DI for application services
  100. services.AddScoped<IUserService, UserService>();
  101. // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  102. }
  103. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  104. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  105. {
  106. //if (env.IsDevelopment())
  107. //{
  108. // app.UseDeveloperExceptionPage();
  109. //}
  110. //else
  111. //{
  112. // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  113. // app.UseHsts();
  114. //}
  115. //app.UseHttpsRedirection();
  116. //app.UseMvc();
  117. app.Use(async (ctx, next) =>
  118. {
  119. await next();
  120. if (ctx.Response.StatusCode == 204)
  121. {
  122. ctx.Response.ContentLength = 0;
  123. }
  124. });
  125. // app.UseCors("CorsPolicy");
  126. app.UseSignalR(routes =>
  127. {
  128. routes.MapHub<AuthHub>("/authhub");
  129. });
  130. //if (env.IsDevelopment())
  131. //{
  132. // app.UseDeveloperExceptionPage();
  133. //}
  134. //else
  135. //{
  136. // app.UseHsts();
  137. //}
  138. WK_KLI_LAPS_COMMONTOOL_Service.App_Data.AppContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
  139. app.UseAuthentication();
  140. app.UseHttpsRedirection();
  141. // app.UseMvc();
  142. app.UseRouting();
  143. app.UseCors("CorsPolicy");
  144. app.UseAuthorization();
  145. app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
  146. }
  147. }
  148. }