-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartup.cs
210 lines (175 loc) · 7.33 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
using Golden_Leaf_Back_End.Filters;
using Golden_Leaf_Back_End.Models;
using Golden_Leaf_Back_End.Models.CategoryModels;
using Golden_Leaf_Back_End.Models.ClerkModels;
using Golden_Leaf_Back_End.Models.ClientModels;
using Golden_Leaf_Back_End.Models.OrderModels;
using Golden_Leaf_Back_End.Models.PaymentModels;
using Golden_Leaf_Back_End.Models.ProductModels;
using Golden_Leaf_Back_End.Settings;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using System;
using System.Text;
namespace Golden_Leaf_Back_End
{
public class Startup
{
private readonly IConfiguration configuration;
private readonly IWebHostEnvironment environment;
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
this.configuration = configuration;
this.environment = environment;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var jwt = configuration.GetSection("Development").Get<JWT>();
services.AddDbContextPool<GoldenLeafContext>(options =>
{
if (environment.IsDevelopment())
{
options.UseSqlServer(configuration.GetConnectionString("Development"));
}
if (environment.IsProduction())
{
jwt = configuration.GetSection("Production").Get<JWT>();
options.UseNpgsql(configuration.GetConnectionString("Production"));
}
});
//Identity
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.User.AllowedUserNameCharacters = null; //Validation will be done in the model;
})
.AddEntityFrameworkStores<GoldenLeafContext>()
.AddDefaultTokenProviders();
//Injection
services.AddScoped<ICategoryRepository, CategoryRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<IClientRepository, ClientRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IPaymentRepository, PaymentRepository>();
//CORS Policy
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyMethod().AllowAnyHeader().WithOrigins(jwt.Audience);
});
});
//Authentication
services.AddSingleton(jwt);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwt.Issuer,
ValidateAudience = true,
ValidAudience = jwt.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)),
};
}
);
//I want to use my own state validation implemented in my exception filter.
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddApiVersioning();
services.AddControllers(options =>
{
options.Filters.Add(typeof(ErrorResponseFilter));
}).AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
//APi documentation
services.AddSwaggerGen(options =>
{
options.EnableAnnotations();
//Fix enums conflicts.
options.CustomSchemaIds(type => type.FullName);
// definition of the security scheme used
options.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = JwtBearerDefaults.AuthenticationScheme
});
//Defines what operations use the abome scheme - (all).
options.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = JwtBearerDefaults.AuthenticationScheme
}
},
Array.Empty<string>()
}});
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Golden Leaf api",
Description = "Documentação da api de estoque de produtos.",
Contact = new OpenApiContact
{
Name = "Renan Rosa",
Email = "renannojosa@gmail.com"
},
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Golden Leaf v1");
options.DefaultModelsExpandDepth(-1);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}