-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
220 lines (185 loc) · 6.88 KB
/
Copy pathProgram.cs
File metadata and controls
220 lines (185 loc) · 6.88 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using SignalRCookieBaseAuth.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// SignalR
builder.Services.AddSignalR();
// Domain Configuration
var baseDomain = builder.Configuration["Domain:BaseDomain"] ?? "example.com";
var cookieDomain = builder.Configuration["Domain:CookieDomain"] ?? $".{baseDomain}";
var corsOrigins = builder.Configuration.GetSection("Domain:CorsOrigins").Get<string[]>()
?? new[] { $"https://{baseDomain}", $"https://www.{baseDomain}" };
// CORS Configuration for subdomains
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSubdomains", policy =>
{
policy.WithOrigins(corsOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() // Important for cookies
.SetIsOriginAllowed(origin =>
{
// Development ortamında localhost'a izin ver
if (builder.Environment.IsDevelopment())
{
try
{
var uri = new Uri(origin);
if (uri.Host == "localhost" || uri.Host == "127.0.0.1")
{
return true;
}
}
catch
{
// Ignore
}
}
// Allow any subdomain of baseDomain
try
{
var uri = new Uri(origin);
return uri.Host == baseDomain || uri.Host.EndsWith($".{baseDomain}");
}
catch
{
return false;
}
});
});
});
// JWT Configuration
var jwtSecret = builder.Configuration["Jwt:Secret"] ?? "YourSuperSecretKeyThatIsAtLeast32CharactersLong!";
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? $"https://api.{baseDomain}";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? $"https://{baseDomain}";
var key = Encoding.UTF8.GetBytes(jwtSecret);
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 = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(key),
ClockSkew = TimeSpan.Zero
};
// SignalR için cookie'den token okuma
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
// SignalR WebSocket ve Long Polling isteklerinde cookie'den token oku
var accessToken = context.Request.Cookies["access_token"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Static files (wwwroot klasörü için)
app.UseStaticFiles();
// Default files (index.html için)
app.UseDefaultFiles();
// CORS must be before UseAuthentication
app.UseCors("AllowSubdomains");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Login endpoint - Token'ı cookie'ye set eder
app.MapPost("/api/auth/login", (HttpContext context, LoginRequest request) =>
{
// Basit bir demo için hardcoded kullanıcı
// Gerçek uygulamada veritabanından kontrol edilmelidir
if (request.Username == "test" && request.Password == "test123")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, request.Username),
new Claim(ClaimTypes.NameIdentifier, "1"),
new Claim(JwtRegisteredClaimNames.Sub, request.Username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(24),
Issuer = jwtIssuer,
Audience = jwtAudience,
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
// HttpOnly, Secure, SameSite=None cookie set et
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = !app.Environment.IsDevelopment() || context.Request.IsHttps, // Development'ta HTTP için false
SameSite = app.Environment.IsDevelopment() ? SameSiteMode.Lax : SameSiteMode.None, // Development'ta Lax
Expires = DateTime.UtcNow.AddHours(24),
Path = "/"
};
// Localhost için domain set etme (localhost özel bir domain)
// Production'da domain set et
if (!app.Environment.IsDevelopment() && !string.IsNullOrEmpty(cookieDomain))
{
cookieOptions.Domain = cookieDomain;
}
context.Response.Cookies.Append("access_token", tokenString, cookieOptions);
return Results.Ok(new { message = "Login successful", username = request.Username });
}
return Results.Unauthorized();
})
.AllowAnonymous();
// Logout endpoint
app.MapPost("/api/auth/logout", (HttpContext context) =>
{
var logoutCookieOptions = new CookieOptions
{
Path = "/"
};
// Localhost için domain set etme
if (!app.Environment.IsDevelopment() && !string.IsNullOrEmpty(cookieDomain))
{
logoutCookieOptions.Domain = cookieDomain;
}
context.Response.Cookies.Delete("access_token", logoutCookieOptions);
return Results.Ok(new { message = "Logout successful" });
})
.AllowAnonymous();
// SignalR Hub endpoint
app.MapHub<ChatHub>("/chatHub");
app.Run();
// Login request model
public record LoginRequest(string Username, string Password);