-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
179 lines (158 loc) · 7.27 KB
/
Copy pathProgram.cs
File metadata and controls
179 lines (158 loc) · 7.27 KB
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
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using MinimalChat.API.Hubs;
using MinimalChat.API.Middleware;
using MinimalChat.Domain.Helpers;
using MinimalChat.Domain.Interfaces;
using MinimalChat.Domain.Models;
using MinmalChat.Data.Context;
using MinmalChat.Data.Repository;
using MinmalChat.Data.Services;
using System.Text;
namespace MinimalChat.API
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Database connection string configuration
builder.Services.AddDbContextPool<MinimalChatDbContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString("MinimalChatEntities"));
options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()));
});
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("JWT"));
// For Identity Users
builder.Services.AddIdentity<MinimalChatUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 6;
}).AddEntityFrameworkStores<MinimalChatDbContext>().AddDefaultTokenProviders();
// Configures authentication services with JWT Bearer authentication.
ConfigurationManager Configuration = builder.Configuration;
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
//Adds JWT Bearer authentication options to the authentication services.
.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"])),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
//builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddAutoMapper(typeof(AutoMapperProfiles));
// Registering scoped services for repository interfaces.
// This allows for the use of dependency injection to provide instances of these repositories
// to various parts of the application, ensuring data access is scoped to the current request.
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IMessageService, MessageService>();
builder.Services.AddScoped<ILogService, LogService>();
builder.Services.AddScoped<IGroupService, GroupService>();
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
// Add SignalR Service
builder.Services.AddSignalR();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Configure CORS (Cross-Origin Resource Sharing) policy
// Allow requests from url origin ( "http://localhost:4200")
// Allow any HTTP method (GET, POST, PUT, DELETE, etc.)
// Allow any HTTP headers in the request
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder =>
{
builder
.WithOrigins("http://localhost:4200") // Allow requests from your Angular app's URL
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials(); // Allow credentials (cookies, Authorization header)
});
});
// Define and configure Swagger documentation settings for API.
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "IdentityApi", Version = "v1" });
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please Enter a valid Token!",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
});
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
try
{
var dbContext = serviceProvider.GetRequiredService<MinimalChatDbContext>();
dbContext.Database.Migrate();
}
catch (Exception ex)
{
throw new Exception($"Error applying migrations: {ex.Message}");
}
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("AllowOrigin");
app.UseAuthentication();
app.UseAuthorization();
// Request Logging Middleware
app.UseRequestLoggingMiddleware();
app.MapControllers();
// chatHub for realtime chat
app.MapHub<ChatHub>("/chatHub");
app.Run();
}
}
}