· 6 years ago · Oct 02, 2019, 04:38 PM
1using Kunmispay.Models;
2using Microsoft.AspNetCore.Builder;
3using Microsoft.AspNetCore.Hosting;
4using Swashbuckle.AspNetCore.Swagger;
5using Microsoft.AspNetCore.HttpsPolicy;
6using Microsoft.AspNetCore.Mvc;
7using Microsoft.AspNetCore.SpaServices.AngularCli;
8using Microsoft.EntityFrameworkCore;
9using Microsoft.Extensions.Configuration;
10using Microsoft.Extensions.DependencyInjection;
11using Microsoft.Net.Http.Headers;
12using Kunmispay.Helper;
13using System.Text;
14using Microsoft.AspNetCore.Authentication.JwtBearer;
15using Microsoft.IdentityModel.Tokens;
16using System;
17using Kunmispay.Services;
18using System.Collections.Generic;
19using AutoMapper;
20using Kunmispay.Utility.Profile;
21using Kunmispay.Features.Messaging;
22using Newtonsoft.Json.Serialization;
23
24namespace Kunmispay
25{
26 public class Startup
27 {
28 public Startup(IConfiguration configuration)
29 {
30 Configuration = configuration;
31 }
32
33 public IConfiguration Configuration { get; }
34
35 // This method gets called by the runtime. Use this method to add services to the container.
36 public void ConfigureServices(IServiceCollection services)
37 {
38 //services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
39 //{
40 // builder
41 // .AllowAnyOrigin()
42 // .WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
43 // .AllowAnyMethod()
44 // .AllowCredentials();
45 //}));
46
47 services.AddMvc()
48 .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
49 //.AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver())
50
51 //var config = new AutoMapper.MapperConfiguration(c =>
52 //{
53 // c.AddProfile(new ApplicationProfile());
54 //});
55
56 //var mapper = config.CreateMapper();
57 //services.AddSingleton(mapper);
58 services.AddTransient<IMessageService, MessageService>();
59 services.AddSwaggerGen(c =>
60 {
61 c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
62 var security = new Dictionary<string, IEnumerable<string>>
63 {
64 {"Bearer", new string[] { }},
65 };
66 c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
67 {
68 Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
69 Name = "Authorization",
70 In = "header",
71 Type = "apiKey"
72 });
73 c.AddSecurityRequirement(security);
74 security = new Dictionary<string, IEnumerable<string>>
75 {
76 {"basic", new string[] { }},
77 };
78
79 c.AddSecurityDefinition("basic", new BasicAuthScheme() { Type = "basic" });
80 c.AddSecurityRequirement(security);
81
82 c.CustomSchemaIds(x => x.FullName);
83 });
84
85 var appSettingsSection = Configuration.GetSection("AppSettings");
86 services.Configure<AppSettings>(appSettingsSection);
87 //configure JWT Auth
88 var appSettings = appSettingsSection.Get<AppSettings>();
89 var key = Encoding.ASCII.GetBytes(appSettings.Secret);
90 services.AddAuthentication(x =>
91 {
92 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
93 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
94
95 }
96 ).AddJwtBearer(x => {
97 x.RequireHttpsMetadata = false;
98 x.SaveToken = true;
99 x.TokenValidationParameters = new TokenValidationParameters
100 {
101 ValidateIssuerSigningKey = true,
102 IssuerSigningKey = new SymmetricSecurityKey(key),
103 ValidateIssuer = false,
104 ValidateAudience = false,
105 ValidateLifetime = true,
106 ClockSkew = TimeSpan.Zero
107 };
108
109 });
110 services.AddScoped<IAuth, AuthService>();
111 // In production, the Angular files will be served from this directory
112 services.AddSpaStaticFiles(configuration =>
113 {
114 configuration.RootPath = "ClientApp/dist";
115 });
116
117
118 services.AddEntityFrameworkNpgsql().AddDbContext<Context>(opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
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, IHostingEnvironment env)
124 {
125
126 if (env.IsDevelopment())
127 {
128 app.UseDeveloperExceptionPage();
129 }
130 else
131 {
132 app.UseExceptionHandler("/Error");
133 app.UseHsts();
134 }
135
136 //app.UseCors(options => options.WithOrigins("localhost"));
137
138 app.UseHttpsRedirection();
139 app.UseStaticFiles();
140 app.UseSpaStaticFiles();
141 app.UseAuthentication();
142
143 //app.UseCors("ApiCorsPolicy");
144 app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
145 app.UseMvc(routes =>
146 {
147 routes.MapRoute(
148 name: "default",
149 template: "{controller}/{action=Index}/{id?}");
150 });
151
152 app.UseSwagger();
153 // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
154 // specifying the Swagger JSON endpoint.
155 app.UseSwaggerUI(c =>
156 {
157 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
158 });
159
160 app.UseSpa(spa =>
161 {
162 // To learn more about options for serving an Angular SPA from ASP.NET Core,
163 // see https://go.microsoft.com/fwlink/?linkid=864501
164
165 spa.Options.SourcePath = "ClientApp";
166
167 if (env.IsDevelopment())
168 {
169 spa.UseAngularCliServer(npmScript: "start");
170 }
171 });
172 }
173 }
174}