-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStartup.cs
221 lines (202 loc) · 8.25 KB
/
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using NLog;
using System.IO;
using TenantAPI.Entities;
using TenantAPI.Services;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TenantAPI.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using TenantAPI.Helper;
using Microsoft.AspNetCore.Http;
using TenantAPI.Models;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.FileProviders;
namespace TenantAPI
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
private CorsPolicy GenerateCorsPolicy()
{
var builder = new CorsPolicyBuilder();
builder.AllowAnyHeader();
builder.AllowAnyMethod();
//builder.AllowAnyOrigin(); // For anyone access.
builder.WithOrigins("https://localhost"
, "http://localhost:4200"
, "https://localhost:4200"
, "https://instantwebapi.com");
builder.AllowCredentials();
return builder.Build();
}
public Startup(IConfiguration configuration)
{
LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
//added for Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Tenant API", Version = "v1" });
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "value should be \"bearer <client token>\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
[new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
}] = new List<string>()
});
});
services.AddDbContext<EntitiesContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EntitiesConnection")
));
//email services
services.AddTransient<IEmailSender, SendGridEmailSender>();
services.Configure<SendGridEmailSenderOptions>(options =>
{
options.ApiKey = Configuration["AuthorizeClient:SendGrid:ClientSecret"];
options.SenderEmail = Configuration["AuthorizeClient:SendGrid:ClientId"];
options.SenderName = Configuration["AuthorizeClient:SendGrid:ClientName"];
});
services.ConfigureServices();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins
, GenerateCorsPolicy());
});
//services.AddCors();
services.AddControllers();
services.AddScoped<IAuthenticate, Authenticate>();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(Configuration.GetSection("Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(config =>
{
config.AddPolicy(Policies.Master, Policies.MasterPolicy());
config.AddPolicy(Policies.Manager, Policies.AdminPolicy());
config.AddPolicy(Policies.Crew, Policies.CrewPolicy());
config.AddPolicy(Policies.User, Policies.UserPolicy());
});
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//added for Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
if (env.IsDevelopment())
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Tenant API");
}
else
{
//c.RoutePrefix = "/eStoreAPI";// add your virtual path here.
c.SwaggerEndpoint("/TenantAPI/swagger/v1/swagger.json", "Tenant API");
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
app.UseHsts(hsts => hsts.MaxAge(365));
app.UseXContentTypeOptions();
app.UseReferrerPolicy(opts => opts.NoReferrer());
const string cacheMaxAge = "604800"; //7 days
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, Globals.STATIC_FOLDER)),
RequestPath = "/StaticFiles"
, //For caching
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cacheMaxAge}");
}
});
//Registered after static files, to set headers for dynamic content.
app.UseXfo(xfo => xfo.Deny());
app.UseRedirectValidation(opts =>
{
opts.AllowedDestinations("https://localhost:4200/#/");
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}