✨
This commit is contained in:
79
StopShopping.Api/Extensions/CommonServiceCollections.cs
Normal file
79
StopShopping.Api/Extensions/CommonServiceCollections.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using StopShopping.Api.Middlewares;
|
||||
using StopShopping.Services;
|
||||
using StopShopping.Services.Extensions;
|
||||
|
||||
namespace StopShopping.Api.Extensions;
|
||||
|
||||
public static class CommonServiceCollections
|
||||
{
|
||||
public static IServiceCollection AddCommonServices(
|
||||
this IServiceCollection services,
|
||||
string corsPolicy,
|
||||
IConfigurationSection jwtConfiguration,
|
||||
IConfigurationSection appConfiguration,
|
||||
bool isDevelopment)
|
||||
{
|
||||
var appOptions = appConfiguration.Get<AppOptions>();
|
||||
services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy(corsPolicy, policy =>
|
||||
{
|
||||
policy.AllowAnyHeader();
|
||||
policy.AllowAnyMethod();
|
||||
policy.WithOrigins(appOptions!.CorsAllowedOrigins);
|
||||
policy.AllowCredentials();
|
||||
});
|
||||
});
|
||||
services.ConfigureHttpJsonOptions(options =>
|
||||
{
|
||||
options.SerializerOptions.Converters.Add(
|
||||
new JsonStringEnumConverter(namingPolicy: null, allowIntegerValues: true));
|
||||
});
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddOpenApi(options =>
|
||||
{
|
||||
options.AddDocumentTransformer<BearerOpenApiDocumentTransformer>();
|
||||
options.AddSchemaTransformer<EnumOpenApiSchemaTransformer>();
|
||||
});
|
||||
services.AddProblemDetails(options =>
|
||||
{
|
||||
options.CustomizeProblemDetails = (context) =>
|
||||
{
|
||||
if (context.ProblemDetails is HttpValidationProblemDetails problemDetails)
|
||||
{
|
||||
problemDetails.AddErrorCode(ProblemDetailsCodes.ParametersValidationFailed);
|
||||
var errors = problemDetails.Errors.Select(e => string.Join(',', e.Value));
|
||||
if (null != errors)
|
||||
problemDetails.Detail = string.Join(',', errors);
|
||||
}
|
||||
};
|
||||
});
|
||||
services.AddValidation();
|
||||
services.AddDistributedMemoryCache();
|
||||
|
||||
services.AddAuthServices(jwtConfiguration);
|
||||
|
||||
services.AddAntiforgery(options =>
|
||||
{
|
||||
var jwtOptions = jwtConfiguration.Get<JwtOptions>();
|
||||
|
||||
options.HeaderName = appOptions!.CSRFHeaderName;
|
||||
options.Cookie.MaxAge = TimeSpan.FromSeconds(jwtOptions!.RefreshTokenExpiresIn);
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.Name = appOptions.CSRFCookieName;
|
||||
if (isDevelopment)
|
||||
{
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
}
|
||||
else
|
||||
{
|
||||
options.Cookie.SameSite = SameSiteMode.None;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.Cookie.Domain = appOptions.CookieDomain;
|
||||
}
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user