-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
164 lines (145 loc) · 5.77 KB
/
Program.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
using System.Text;
using System.Text.Json.Serialization;
using FAKA.Server;
using FAKA.Server.Auth;
using FAKA.Server.Data;
using FAKA.Server.Filters;
using FAKA.Server.Models;
using FAKA.Server.Payment;
using FAKA.Server.Payment.Gateways;
using FAKA.Server.Services;
using FluentEmail.MailKitSmtp;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
// Add services to the container.
// For Entity Framework
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("ApplicationDbContext") ??
throw new InvalidOperationException("Connection string 'ApplicationDbContext' not found.")));
// For Identity
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
//password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Adding Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = configuration["JWT:ValidAudience"],
ValidIssuer = configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"] ?? throw new InvalidOperationException("JWT:Secret not found.")))
};
});
// adding controllers
builder.Services.AddControllers(options => { options.Filters.Add<CustomResultFilterAttribute>(); })
.AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
//邮件服务
builder.Services.AddFluentEmail(configuration["SMTP:Sender"], configuration["SMTP:SenderName"])
.AddLiquidRenderer()
.AddMailKitSender(new SmtpClientOptions
{
Server = configuration["SMTP:Server"],
Port = int.Parse(configuration["SMTP:Port"] ?? throw new InvalidOperationException("SMTP:Port not found or invalid.")),
User = configuration["SMTP:Username"],
Password = configuration["SMTP:Password"],
RequiresAuthentication = (configuration["SMTP:Password"] != null && configuration["SMTP:Username"] != null)
});
//依赖注入(DI)
//自定义鉴权回复中间件
builder.Services.AddSingleton<
IAuthorizationMiddlewareResultHandler, AuthMiddlewareResultHandler>();
//---------------------------------支付接口----------------------------------
builder.Services.AddTransient<IPaymentGateway, StripeAlipayPaymentGateway>();
builder.Services.AddTransient<IPaymentGateway, AlipayWeb>();
builder.Services.AddTransient<PaymentGatewayFactory>();
//---------------------------------服务------------------------------------
builder.Services.AddTransient<OrderService>();
builder.Services.AddTransient<TransactionService>();
builder.Services.AddTransient<AuthService>();
builder.Services.AddTransient<GatewayService>();
builder.Services.AddTransient<EmailService>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "FAKA API", Version = "v1" });
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid jwt token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
// adding cors https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0
const string myAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(myAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("*")
.WithExposedHeaders("Authorization")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
//add automapper
builder.Services.AddAutoMapper(typeof(OrganizationProfile));
//add payment gateway and config name
builder.Services.Configure<Dictionary<string, Dictionary<string, object>>>(configuration.GetSection("PaymentGateways"));
//add signalr
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(myAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();