-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.cs
More file actions
653 lines (559 loc) · 29.2 KB
/
AuthController.cs
File metadata and controls
653 lines (559 loc) · 29.2 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Taskdeck.Api.Contracts;
using Taskdeck.Api.Extensions;
using Taskdeck.Api.Filters;
using Taskdeck.Api.RateLimiting;
using Taskdeck.Application.DTOs;
using Taskdeck.Application.Interfaces;
using Taskdeck.Application.Services;
using Taskdeck.Domain.Entities;
using Taskdeck.Domain.Exceptions;
using AuthenticationService = Taskdeck.Application.Services.AuthenticationService;
namespace Taskdeck.Api.Controllers;
public record ChangePasswordRequest(string CurrentPassword, string NewPassword, string? MfaCode = null);
public record ExchangeCodeRequest(string Code);
public record LinkExchangeRequest(string Code);
/// <summary>
/// Authentication endpoints — register, login, change password, and GitHub OAuth flow.
/// All endpoints return a JWT token on successful authentication.
/// </summary>
[ApiController]
[Route("api/auth")]
[Produces("application/json")]
public class AuthController : AuthenticatedControllerBase
{
private readonly AuthenticationService _authService;
private readonly GitHubOAuthSettings _gitHubOAuthSettings;
private readonly OidcSettings _oidcSettings;
private readonly MfaService _mfaService;
private readonly IUnitOfWork _unitOfWork;
public AuthController(
AuthenticationService authService,
GitHubOAuthSettings gitHubOAuthSettings,
OidcSettings oidcSettings,
MfaService mfaService,
IUserContext userContext,
IUnitOfWork unitOfWork)
: base(userContext)
{
_authService = authService;
_gitHubOAuthSettings = gitHubOAuthSettings;
_oidcSettings = oidcSettings;
_mfaService = mfaService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Authenticate with username/email and password. Returns a JWT token.
/// </summary>
/// <param name="dto">Login credentials.</param>
/// <returns>JWT token and user profile.</returns>
/// <response code="200">Login successful — JWT token returned.</response>
/// <response code="401">Invalid credentials.</response>
/// <response code="429">Rate limit exceeded.</response>
[HttpPost("login")]
[SuppressModelStateValidation]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
[ProducesResponseType(typeof(AuthResultDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status429TooManyRequests)]
public async Task<IActionResult> Login([FromBody] LoginDto? dto)
{
if (dto is null
|| string.IsNullOrWhiteSpace(dto.UsernameOrEmail)
|| string.IsNullOrWhiteSpace(dto.Password))
{
return Unauthorized(new ApiErrorResponse(
ErrorCodes.AuthenticationFailed,
"Invalid username/email or password"));
}
var result = await _authService.LoginAsync(dto!);
return result.IsSuccess ? Ok(result.Value) : result.ToErrorActionResult();
}
/// <summary>
/// Register a new user account. Returns a JWT token.
/// </summary>
/// <param name="dto">Registration details: username, email, password.</param>
/// <returns>JWT token and user profile.</returns>
/// <response code="200">Registration successful — JWT token returned.</response>
/// <response code="400">Validation error (e.g., duplicate username/email).</response>
/// <response code="429">Rate limit exceeded.</response>
[HttpPost("register")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
[ProducesResponseType(typeof(AuthResultDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status429TooManyRequests)]
public async Task<IActionResult> Register([FromBody] CreateUserDto dto)
{
var result = await _authService.RegisterAsync(dto);
return result.IsSuccess ? Ok(result.Value) : result.ToErrorActionResult();
}
/// <summary>
/// Change the password for the authenticated caller.
/// The target user is always derived from the JWT — client-supplied user IDs are not accepted.
/// When MFA is enabled and RequireMfaForSensitiveActions is true, a valid MFA code is required.
/// </summary>
/// <param name="request">Current password, new password, and optional MFA code.</param>
/// <response code="204">Password changed successfully.</response>
/// <response code="400">Validation error.</response>
/// <response code="401">Not authenticated or current password is incorrect.</response>
/// <response code="403">MFA verification required but not provided or invalid.</response>
/// <response code="429">Rate limit exceeded.</response>
[HttpPost("change-password")]
[Authorize]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status403Forbidden)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status429TooManyRequests)]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
{
if (!TryGetCurrentUserId(out var callerUserId, out var errorResult))
return errorResult!;
// Enforce MFA for sensitive actions when policy requires it
if (await _mfaService.IsMfaRequiredForSensitiveActionAsync(callerUserId))
{
if (string.IsNullOrWhiteSpace(request.MfaCode))
return StatusCode(StatusCodes.Status403Forbidden, new ApiErrorResponse(
ErrorCodes.Forbidden, "MFA verification is required for this action"));
var mfaResult = await _mfaService.VerifyCodeAsync(callerUserId, request.MfaCode);
if (!mfaResult.IsSuccess)
return StatusCode(StatusCodes.Status403Forbidden, new ApiErrorResponse(
ErrorCodes.AuthenticationFailed, "Invalid MFA verification code"));
}
var result = await _authService.ChangePasswordAsync(callerUserId, request.CurrentPassword, request.NewPassword);
return result.IsSuccess ? NoContent() : result.ToErrorActionResult();
}
/// <summary>
/// Initiates GitHub OAuth login or account-linking flow. Only available when GitHub OAuth is configured.
/// The flow is determined entirely from server-side state: if the caller is already authenticated
/// (carries a valid JWT), this starts an account-linking flow bound to their identity; otherwise
/// it starts a normal login flow. The client must NOT supply a mode parameter -- the server
/// derives the intent from authentication state to prevent user-controlled bypass.
/// </summary>
[HttpGet("github/login")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public IActionResult GitHubLogin([FromQuery] string? returnUrl = null)
{
if (!_gitHubOAuthSettings.IsConfigured)
return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, "GitHub OAuth is not configured"));
// Validate returnUrl to prevent open redirect
if (!string.IsNullOrWhiteSpace(returnUrl) && !Url.IsLocalUrl(returnUrl))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Invalid return URL"));
var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
RedirectUri = Url.Action(nameof(GitHubCallback), new { returnUrl }),
Items = { { "LoginProvider", "GitHub" } }
};
// Derive flow from server-side authentication state only.
// Never use a user-supplied "mode" query parameter -- that would allow an attacker
// to bypass or force the sensitive account-linking branch (CWE-807 / CodeQL
// "user-controlled bypass of sensitive method").
// If the caller is already authenticated (valid JWT), treat this as a link request.
if (TryGetCurrentUserId(out var callerUserId, out _))
{
properties.Items["mode"] = "link";
properties.Items["link_user_id"] = callerUserId.ToString();
}
return Challenge(properties, "GitHub");
}
/// <summary>
/// Handles the GitHub OAuth callback, creates/links the user, and redirects with a JWT token.
/// </summary>
[HttpGet("github/callback")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public async Task<IActionResult> GitHubCallback([FromQuery] string? returnUrl = null)
{
if (!_gitHubOAuthSettings.IsConfigured)
return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, "GitHub OAuth is not configured"));
var authenticateResult = await HttpContext.AuthenticateAsync("GitHub");
if (!authenticateResult.Succeeded || authenticateResult.Principal == null)
{
return Unauthorized(new ApiErrorResponse(
ErrorCodes.AuthenticationFailed,
"GitHub authentication failed"));
}
var claims = authenticateResult.Principal.Claims.ToList();
var providerUserId = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
var username = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name)?.Value
?? claims.FirstOrDefault(c => c.Type == "urn:github:login")?.Value;
var email = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
var displayName = claims.FirstOrDefault(c => c.Type == "urn:github:name")?.Value;
var avatarUrl = claims.FirstOrDefault(c => c.Type == "urn:github:avatar")?.Value;
if (string.IsNullOrWhiteSpace(providerUserId))
{
return Unauthorized(new ApiErrorResponse(
ErrorCodes.AuthenticationFailed,
"GitHub did not return a user identifier"));
}
// Sign out the temporary cookie used during the OAuth handshake
await HttpContext.SignOutAsync("GitHub");
// Determine if this is a link flow from the tamper-proof OAuth state ONLY.
// Never trust the query string for mode detection -- attacker could append ?mode=link.
var isLinkMode = false;
Guid linkUserId = Guid.Empty;
if (authenticateResult.Properties?.Items.TryGetValue("mode", out var stateMode) == true
&& stateMode == "link")
{
isLinkMode = true;
if (authenticateResult.Properties.Items.TryGetValue("link_user_id", out var linkUserIdStr)
&& Guid.TryParse(linkUserIdStr, out var parsedLinkUserId))
{
linkUserId = parsedLinkUserId;
}
}
// Account linking flow: store the GitHub identity as a link code bound to the user
if (isLinkMode)
{
if (linkUserId == Guid.Empty)
{
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError,
"Account linking requires an authenticated session"));
}
var linkCode = GenerateAuthCode();
var providerData = JsonSerializer.Serialize(new
{
provider = "GitHub",
providerUserId,
displayName,
avatarUrl
});
var linkAuthCode = OAuthAuthCode.CreateForLinking(
code: linkCode,
initiatingUserId: linkUserId,
providerData: providerData,
expiresAt: DateTimeOffset.UtcNow.AddSeconds(60));
await _unitOfWork.OAuthAuthCodes.AddAsync(linkAuthCode);
await _unitOfWork.SaveChangesAsync();
var linkReturnUrl = !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)
? returnUrl
: "/";
var linkSeparator = linkReturnUrl.Contains('?') ? "&" : "?";
return Redirect($"{linkReturnUrl}{linkSeparator}oauth_link_code={Uri.EscapeDataString(linkCode)}");
}
// Normal login flow
// GitHub may not return an email if user's email is private
if (string.IsNullOrWhiteSpace(email))
email = $"{providerUserId}@users.noreply.github.com";
if (string.IsNullOrWhiteSpace(username))
username = $"github-user-{providerUserId}";
var dto = new ExternalLoginDto(
Provider: "GitHub",
ProviderUserId: providerUserId,
Username: username,
Email: email,
DisplayName: displayName,
AvatarUrl: avatarUrl);
var result = await _authService.ExternalLoginAsync(dto);
if (!result.IsSuccess)
return result.ToErrorActionResult();
// Store only the user ID in the auth code -- JWT is re-issued at exchange time.
// This avoids storing plaintext JWTs in the database.
var code = GenerateAuthCode();
var authCode = new OAuthAuthCode(
code: code,
userId: result.Value.User.Id,
token: "placeholder", // Not stored; JWT re-issued at exchange
expiresAt: DateTimeOffset.UtcNow.AddSeconds(60));
await _unitOfWork.OAuthAuthCodes.AddAsync(authCode);
await _unitOfWork.SaveChangesAsync();
// Best-effort cleanup of expired/consumed codes (runs in the same request scope)
await CleanupExpiredCodesAsync();
var safeReturnUrl = !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)
? returnUrl
: "/";
var separator = safeReturnUrl.Contains('?') ? "&" : "?";
return Redirect($"{safeReturnUrl}{separator}oauth_code={Uri.EscapeDataString(code)}");
}
/// <summary>
/// Exchanges a short-lived OAuth authorization code for a JWT token.
/// The code is single-use and expires after 60 seconds.
/// JWT is re-issued fresh at exchange time -- never stored in the database.
/// </summary>
[HttpPost("github/exchange")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public async Task<IActionResult> ExchangeCode([FromBody] ExchangeCodeRequest request)
{
// Use a single generic error message for all failure modes to prevent
// attackers from enumerating codes or determining their state.
const string genericError = "Invalid or expired code";
if (string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Code is required"));
// Read the code to check purpose (pre-filter before atomic consume)
var authCode = await _unitOfWork.OAuthAuthCodes.GetByCodeAsync(request.Code);
if (authCode == null || authCode.IsLinkingCode || authCode.IsExpired || authCode.IsConsumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
// Atomically consume the code — prevents race conditions with concurrent requests.
// The SQL also enforces expiry check to close the TOCTOU window.
var consumed = await _unitOfWork.OAuthAuthCodes.TryConsumeAtomicAsync(request.Code);
if (!consumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
// Look up the user and re-issue a fresh JWT (never stored in DB)
var user = await _unitOfWork.Users.GetByIdAsync(authCode.UserId);
if (user == null)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
var userDto = new UserDto(
user.Id,
user.Username,
user.Email,
user.DefaultRole,
user.IsActive,
user.CreatedAt,
user.UpdatedAt);
// Re-issue JWT at exchange time instead of reading stored token
var freshToken = _authService.GenerateJwtToken(user);
return Ok(new AuthResultDto(freshToken, userDto));
}
/// <summary>
/// Exchanges a link code and associates the GitHub account with the authenticated user.
/// Requires a valid JWT session. The link code must have been initiated by the same user
/// (CSRF protection: code is bound to the initiating user's identity).
/// </summary>
[HttpPost("github/link")]
[Authorize]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
[ProducesResponseType(typeof(LinkedAccountDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status409Conflict)]
public async Task<IActionResult> LinkGitHub([FromBody] LinkExchangeRequest request)
{
const string genericError = "Invalid or expired link code";
if (!_gitHubOAuthSettings.IsConfigured)
return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, "GitHub OAuth is not configured"));
if (!TryGetCurrentUserId(out var callerUserId, out var errorResult))
return errorResult!;
if (string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Link code is required"));
// Look up and validate the link code with uniform error messages
var authCode = await _unitOfWork.OAuthAuthCodes.GetByCodeAsync(request.Code);
if (authCode == null || !authCode.IsLinkingCode || authCode.IsExpired || authCode.IsConsumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
// CSRF protection: verify the link code was initiated by the same user who is
// exchanging it. This prevents an attacker from generating a link code and
// tricking a victim into exchanging it.
if (authCode.UserId != callerUserId)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
// Atomically consume the code (also checks expiry in SQL to close TOCTOU window)
var consumed = await _unitOfWork.OAuthAuthCodes.TryConsumeAtomicAsync(request.Code);
if (!consumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
// Parse the provider data from the link code.
// Wrap in try-catch to prevent 500 errors from malformed JSON (should not happen in normal
// operation, but defensive coding for any unexpected data corruption).
if (string.IsNullOrWhiteSpace(authCode.ProviderData))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Link code contains no provider data"));
string? provider;
string? providerUserId;
string? displayName;
string? avatarUrl;
try
{
var providerInfo = JsonSerializer.Deserialize<JsonElement>(authCode.ProviderData);
provider = providerInfo.GetProperty("provider").GetString() ?? "GitHub";
providerUserId = providerInfo.GetProperty("providerUserId").GetString();
displayName = providerInfo.TryGetProperty("displayName", out var dn) ? dn.GetString() : null;
avatarUrl = providerInfo.TryGetProperty("avatarUrl", out var av) ? av.GetString() : null;
}
catch (JsonException)
{
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Link code contains invalid provider data"));
}
catch (KeyNotFoundException)
{
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Link code is missing required provider fields"));
}
if (string.IsNullOrWhiteSpace(providerUserId))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Provider user ID is missing from link code"));
var result = await _authService.CompleteAccountLinkAsync(callerUserId, provider, providerUserId, displayName, avatarUrl);
return result.IsSuccess ? Ok(result.Value) : result.ToErrorActionResult();
}
/// <summary>
/// Unlinks a GitHub account from the authenticated user.
/// </summary>
[HttpDelete("github/link")]
[Authorize]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status404NotFound)]
public async Task<IActionResult> UnlinkGitHub()
{
if (!TryGetCurrentUserId(out var callerUserId, out var errorResult))
return errorResult!;
var result = await _authService.UnlinkExternalLoginAsync(callerUserId, "GitHub");
return result.IsSuccess ? NoContent() : result.ToErrorActionResult();
}
/// <summary>
/// Returns the external logins linked to the authenticated user.
/// </summary>
[HttpGet("linked-accounts")]
[Authorize]
[ProducesResponseType(typeof(IEnumerable<LinkedAccountDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiErrorResponse), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetLinkedAccounts()
{
if (!TryGetCurrentUserId(out var callerUserId, out var errorResult))
return errorResult!;
var logins = await _unitOfWork.ExternalLogins.GetByUserIdAsync(callerUserId);
var dtos = logins.Select(l => new LinkedAccountDto(
l.Provider,
l.ProviderUserId,
l.ProviderDisplayName,
l.AvatarUrl,
l.CreatedAt));
return Ok(dtos);
}
/// <summary>
/// Returns available authentication providers on this instance.
/// </summary>
[HttpGet("providers")]
public IActionResult GetProviders()
{
var oidcProviders = _oidcSettings.ConfiguredProviders
.Select(p => new OidcProviderInfoDto(p.Name, p.DisplayName))
.ToList();
return Ok(new
{
GitHub = _gitHubOAuthSettings.IsConfigured,
Oidc = oidcProviders
});
}
/// <summary>
/// Initiates OIDC login flow for a named provider. Only available when the provider is configured.
/// </summary>
[HttpGet("oidc/{providerName}/login")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public IActionResult OidcLogin(string providerName, [FromQuery] string? returnUrl = null)
{
var provider = _oidcSettings.ConfiguredProviders
.FirstOrDefault(p => string.Equals(p.Name, providerName, StringComparison.OrdinalIgnoreCase));
if (provider == null)
return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, $"OIDC provider '{providerName}' is not configured"));
if (!string.IsNullOrWhiteSpace(returnUrl) && !Url.IsLocalUrl(returnUrl))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Invalid return URL"));
var schemeName = $"Oidc_{provider.Name}";
var properties = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(OidcCallback), new { providerName = provider.Name, returnUrl }),
Items = { { "LoginProvider", provider.Name } }
};
return Challenge(properties, schemeName);
}
/// <summary>
/// Handles the OIDC callback, creates/links the user, and redirects with a short-lived code.
/// </summary>
[HttpGet("oidc/{providerName}/callback")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public async Task<IActionResult> OidcCallback(string providerName, [FromQuery] string? returnUrl = null)
{
var provider = _oidcSettings.ConfiguredProviders
.FirstOrDefault(p => string.Equals(p.Name, providerName, StringComparison.OrdinalIgnoreCase));
if (provider == null)
return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, $"OIDC provider '{providerName}' is not configured"));
var schemeName = $"Oidc_{provider.Name}";
var authenticateResult = await HttpContext.AuthenticateAsync(schemeName);
if (!authenticateResult.Succeeded || authenticateResult.Principal == null)
{
return Unauthorized(new ApiErrorResponse(
ErrorCodes.AuthenticationFailed,
$"OIDC authentication with '{provider.DisplayName}' failed"));
}
var claims = authenticateResult.Principal.Claims.ToList();
var providerUserId = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
var username = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name)?.Value
?? claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value;
var email = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
var displayName = claims.FirstOrDefault(c => c.Type == "name")?.Value;
if (string.IsNullOrWhiteSpace(providerUserId))
{
return Unauthorized(new ApiErrorResponse(
ErrorCodes.AuthenticationFailed,
$"OIDC provider '{provider.DisplayName}' did not return a user identifier"));
}
if (string.IsNullOrWhiteSpace(email))
email = $"{provider.Name.ToLowerInvariant()}-{providerUserId}@external.taskdeck.local";
if (string.IsNullOrWhiteSpace(username))
username = $"{provider.Name.ToLowerInvariant()}-user-{providerUserId}";
var dto = new ExternalLoginDto(
Provider: $"oidc_{provider.Name}",
ProviderUserId: providerUserId,
Username: username,
Email: email,
DisplayName: displayName,
AvatarUrl: null);
var result = await _authService.ExternalLoginAsync(dto);
if (!result.IsSuccess)
return result.ToErrorActionResult();
// Sign out the temporary cookie used during the OIDC handshake
await HttpContext.SignOutAsync(AuthenticationRegistration.ExternalAuthenticationScheme);
// Store only the user ID in the auth code -- JWT is re-issued at exchange time.
var code = GenerateAuthCode();
var authCode = new OAuthAuthCode(
code: code,
userId: result.Value.User.Id,
token: "placeholder", // Not stored; JWT re-issued at exchange
expiresAt: DateTimeOffset.UtcNow.AddSeconds(60));
await _unitOfWork.OAuthAuthCodes.AddAsync(authCode);
await _unitOfWork.SaveChangesAsync();
// Best-effort cleanup of expired/consumed codes
await CleanupExpiredCodesAsync();
var safeReturnUrl = !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)
? returnUrl
: "/";
var separator = safeReturnUrl.Contains('?') ? "&" : "?";
return Redirect($"{safeReturnUrl}{separator}oauth_code={Uri.EscapeDataString(code)}&oauth_provider=oidc");
}
/// <summary>
/// Exchanges a short-lived OIDC authorization code for a JWT token.
/// Reuses the same database-backed code store as GitHub OAuth.
/// </summary>
[HttpPost("oidc/exchange")]
[EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)]
public async Task<IActionResult> OidcExchangeCode([FromBody] ExchangeCodeRequest request)
{
const string genericError = "Invalid or expired code";
if (string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Code is required"));
var authCode = await _unitOfWork.OAuthAuthCodes.GetByCodeAsync(request.Code);
if (authCode == null || authCode.IsLinkingCode || authCode.IsExpired || authCode.IsConsumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
var consumed = await _unitOfWork.OAuthAuthCodes.TryConsumeAtomicAsync(request.Code);
if (!consumed)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
var user = await _unitOfWork.Users.GetByIdAsync(authCode.UserId);
if (user == null)
return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, genericError));
var userDto = new UserDto(
user.Id,
user.Username,
user.Email,
user.DefaultRole,
user.IsActive,
user.CreatedAt,
user.UpdatedAt);
var freshToken = _authService.GenerateJwtToken(user);
return Ok(new AuthResultDto(freshToken, userDto));
}
private static string GenerateAuthCode()
{
var bytes = RandomNumberGenerator.GetBytes(32);
return Convert.ToBase64String(bytes).Replace("+", "-").Replace("/", "_").TrimEnd('=');
}
private async Task CleanupExpiredCodesAsync()
{
try
{
await _unitOfWork.OAuthAuthCodes.DeleteExpiredAsync(DateTimeOffset.UtcNow);
}
catch
{
// Cleanup failure is non-critical
}
}
}