-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
77 lines (63 loc) · 2.51 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
using JwtAuthApi.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// 1. Configure the Database Context (Entity Framework Core)
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// 2. Configure ASP.NET Core Identity
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
// 3. Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
// 4. Add CORS Policy
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp", builder =>
builder.WithOrigins("http://localhost:3000") // Allow requests from React frontend
.AllowAnyMethod()
.AllowAnyHeader()
);
});
// 5. Add Controllers support (necessary for MVC actions like Login, Register)
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
}
//app.UseHttpsRedirection();
// 6. Enable CORS
app.UseCors("AllowReactApp"); // Enable the CORS policy
// 7. Enable Authentication and Authorization Middleware
app.UseRouting();
app.UseAuthentication(); // This ensures that authentication is checked for every request
app.UseAuthorization(); // This ensures that the app enforces authorization policies
app.MapControllers(); // This maps the controllers to handle requests like /api/auth/register
app.Run();