-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
96 lines (79 loc) · 2.7 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
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using dotnet_rideShare.Models;
using dotnet_rideShare.Contexts;
using System.Security.Claims;
using dotnet_rideShare.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
var appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
builder.Services.AddSingleton<AppSettings>();
builder.Services.AddSingleton<EmailService>(sp =>
{
var emailConfig = builder.Configuration.GetSection("EmailConfig").Get<EmailConfig>();
return new EmailService(emailConfig);
});
builder.Services.AddCors(options =>
{
options.AddPolicy(appSettings.ApiCorsPolicy,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
var secretKey = Encoding.UTF8.GetBytes(appSettings.Secret);
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = false,
ValidIssuer = appSettings.BearerValidIssuer,
ValidAudience = appSettings.BearerValidAudience,
IssuerSigningKey = new SymmetricSecurityKey(secretKey)
};
});
builder.Services.AddDbContext<DatabaseContext>(options =>
options.UseMySQL(appSettings.ConnectionString));
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Admin"));
options.AddPolicy("UserPolicy", policy => policy.RequireRole("User"));
options.AddPolicy("UserOrAdminPolicy", policy =>
{
policy.RequireAssertion(context =>
context.User.HasClaim(ClaimTypes.Role, "User") ||
context.User.HasClaim(ClaimTypes.Role, "Admin"));
});
});
builder.Services.AddSignalR();
var app = builder.Build();
app.UseHttpsRedirection();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseCors(appSettings.ApiCorsPolicy);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotificationContext>(appSettings.NotificationSocket);
});
app.Run();