source: Farmatiko/Startup.cs@ 8e74e2f

Last change on this file since 8e74e2f was 1db5673, checked in by DimitarSlezenkovski <dslezenkovski@…>, 3 years ago

Fix bugs, add some more

  • Property mode set to 100644
File size: 7.0 KB
Line 
1using Microsoft.AspNetCore.Builder;
2using Microsoft.AspNetCore.Hosting;
3using Microsoft.AspNetCore.SpaServices.AngularCli;
4using Microsoft.Extensions.Configuration;
5using Microsoft.Extensions.DependencyInjection;
6using Microsoft.Extensions.Hosting;
7using FarmatikoData;
8using Microsoft.EntityFrameworkCore;
9using FarmatikoData.FarmatikoRepoInterfaces;
10using FarmatikoData.FarmatikoRepo;
11using FarmatikoServices.FarmatikoServiceInterfaces;
12using FarmatikoServices.Services;
13using Microsoft.Extensions.Logging;
14using Microsoft.AspNetCore.Authentication.JwtBearer;
15using Microsoft.IdentityModel.Tokens;
16using System.Text;
17using FarmatikoServices.Auth;
18using FarmatikoServices.Infrastructure;
19using System;
20using Newtonsoft.Json.Serialization;
21namespace Farmatiko
22{
23 public class Startup
24 {
25 readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
26
27 public Startup(IConfiguration configuration)
28 {
29 Configuration = configuration;
30 }
31
32 public IConfiguration Configuration { get; }
33
34 // This method gets called by the runtime. Use this method to add services to the container.
35 public void ConfigureServices(IServiceCollection services)
36 {
37 services.AddCors(options =>
38 {
39 options.AddPolicy(name: MyAllowSpecificOrigins,
40 builder =>
41 {
42 builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
43 });
44 });
45
46 services.AddControllersWithViews();
47 services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
48 // In production, the Angular files will be served from this directory
49 services.AddSpaStaticFiles(configuration =>
50 {
51 configuration.RootPath = "ClientApp/dist";
52 });
53 var connectionString = Configuration.GetSection("ConnectionStrings").GetValue<string>("FarmatikoConnection");
54 services.AddEntityFrameworkNpgsql().AddDbContext<FarmatikoDataContext>(opt => opt.UseNpgsql(connectionString));
55
56 services.AddScoped<IPHRepo, PHRepo>();
57 services.AddTransient<IRepository, Repository>();
58 services.AddTransient<IAdminRepo, AdminRepo>();
59
60 services.AddTransient<IPHService, PHService>();
61 services.AddTransient<IAdminService, AdminService>();
62 services.AddTransient<IService, Service>();
63
64 services.AddTransient<IProcessJSONService, ProcessJSONService>();
65
66 services.AddTransient<ILogger, Logger<ProcessJSONService>>();
67
68 // services.AddTransient<ISystemService, SystemService>();
69
70
71 var jwtTokenConfig = Configuration.GetSection("jwtTokenConfig").Get<JwtTokenConfig>();
72 services.AddSingleton(jwtTokenConfig);
73
74 services.AddAuthentication(o =>
75 {
76 o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
77 o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
78 o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
79 }).AddJwtBearer(x =>
80 {
81 x.RequireHttpsMetadata = true;
82 x.SaveToken = true;
83 x.TokenValidationParameters = new TokenValidationParameters
84 {
85 ValidateIssuer = true,
86 ValidIssuer = jwtTokenConfig.Issuer,
87 ValidateIssuerSigningKey = true,
88 IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
89 ValidAudience = jwtTokenConfig.Audience,
90 ValidateAudience = true,
91 ValidateLifetime = true,
92 ClockSkew = TimeSpan.FromMinutes(1)
93 };
94 });
95
96 /*.AddJwtBearer(cfg =>
97 {
98 cfg.RequireHttpsMetadata = false;
99 cfg.SaveToken = true;
100 cfg.IncludeErrorDetails = true;
101 cfg.TokenValidationParameters = new TokenValidationParameters()
102 {
103 ValidIssuer = Configuration.GetSection("TokenIssuer").Value,
104 ValidAudience = Configuration.GetSection("TokenIssuer").Value,
105 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecretKey").Value))
106 };
107
108 });
109*/
110 services.AddSingleton<IJwtAuthManager, JwtAuthManager>();
111 services.AddHostedService<JwtRefreshTokenCache>();
112 services.AddScoped<IAuthService, AuthService>();
113 //If we add imgs
114 /*services.Configure<FormOptions>(o => {
115 o.ValueLengthLimit = int.MaxValue;
116 o.MultipartBodyLengthLimit = int.MaxValue;
117 o.MemoryBufferThreshold = int.MaxValue;
118 });*/
119
120 }
121
122 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
123 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
124 {
125 if (env.IsDevelopment())
126 {
127 app.UseDeveloperExceptionPage();
128 }
129 else
130 {
131 app.UseExceptionHandler("/Error");
132 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
133 app.UseHsts();
134 }
135 app.UseExceptionHandler("/Error");
136 app.UseHttpsRedirection();
137 app.UseStaticFiles();
138
139 // if we add imgs
140 /*app.UseStaticFiles(new StaticFileOptions()
141 {
142 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")),
143 RequestPath = new PathString("/wwwroot")
144 });*/
145
146 if (!env.IsDevelopment())
147 {
148 app.UseSpaStaticFiles();
149 }
150
151 app.UseRouting();
152
153 app.UseAuthentication();
154 app.UseAuthorization();
155
156 app.UseCors(MyAllowSpecificOrigins);
157
158 app.UseEndpoints(endpoints =>
159 {
160 endpoints.MapControllerRoute(
161 name: "default",
162 pattern: "api/{controller}/{action=Index}/{id?}");
163 });
164
165 app.UseSpa(spa =>
166 {
167 // To learn more about options for serving an Angular SPA from ASP.NET Core,
168 // see https://go.microsoft.com/fwlink/?linkid=864501
169
170 spa.Options.SourcePath = "ClientApp";
171
172 if (env.IsDevelopment())
173 {
174 spa.UseAngularCliServer(npmScript: "start");
175 }
176 });
177 }
178 }
179}
Note: See TracBrowser for help on using the repository browser.