|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Security.Cryptography; |
| 3 | +using Microsoft.AspNetCore.Authentication; |
1 | 4 | using Microsoft.AspNetCore.Mvc; |
2 | 5 | using Microsoft.AspNetCore.RateLimiting; |
3 | 6 | using Taskdeck.Api.Contracts; |
|
7 | 10 | using Taskdeck.Application.DTOs; |
8 | 11 | using Taskdeck.Application.Services; |
9 | 12 | using Taskdeck.Domain.Exceptions; |
| 13 | +using AuthenticationService = Taskdeck.Application.Services.AuthenticationService; |
10 | 14 |
|
11 | 15 | namespace Taskdeck.Api.Controllers; |
12 | 16 |
|
13 | 17 | public record ChangePasswordRequest(Guid UserId, string CurrentPassword, string NewPassword); |
| 18 | +public record ExchangeCodeRequest(string Code); |
14 | 19 |
|
15 | 20 | [ApiController] |
16 | 21 | [Route("api/auth")] |
17 | 22 | public class AuthController : ControllerBase |
18 | 23 | { |
19 | 24 | private readonly AuthenticationService _authService; |
| 25 | + private readonly GitHubOAuthSettings _gitHubOAuthSettings; |
20 | 26 |
|
21 | | - public AuthController(AuthenticationService authService) |
| 27 | + // Short-lived, single-use authorization codes to avoid exposing JWT in URLs. |
| 28 | + // Key: code, Value: (token, expiry). Codes expire after 60 seconds. |
| 29 | + private static readonly ConcurrentDictionary<string, (AuthResultDto Result, DateTimeOffset Expiry)> _authCodes = new(); |
| 30 | + |
| 31 | + public AuthController(AuthenticationService authService, GitHubOAuthSettings gitHubOAuthSettings) |
22 | 32 | { |
23 | 33 | _authService = authService; |
| 34 | + _gitHubOAuthSettings = gitHubOAuthSettings; |
24 | 35 | } |
25 | 36 |
|
26 | 37 | [HttpPost("login")] |
@@ -56,4 +67,145 @@ public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest |
56 | 67 | var result = await _authService.ChangePasswordAsync(request.UserId, request.CurrentPassword, request.NewPassword); |
57 | 68 | return result.IsSuccess ? NoContent() : result.ToErrorActionResult(); |
58 | 69 | } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Initiates GitHub OAuth login flow. Only available when GitHub OAuth is configured. |
| 73 | + /// </summary> |
| 74 | + [HttpGet("github/login")] |
| 75 | + [EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)] |
| 76 | + public IActionResult GitHubLogin([FromQuery] string? returnUrl = null) |
| 77 | + { |
| 78 | + if (!_gitHubOAuthSettings.IsConfigured) |
| 79 | + return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, "GitHub OAuth is not configured")); |
| 80 | + |
| 81 | + // Validate returnUrl to prevent open redirect |
| 82 | + if (!string.IsNullOrWhiteSpace(returnUrl) && !Url.IsLocalUrl(returnUrl)) |
| 83 | + return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Invalid return URL")); |
| 84 | + |
| 85 | + var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties |
| 86 | + { |
| 87 | + RedirectUri = Url.Action(nameof(GitHubCallback), new { returnUrl }), |
| 88 | + Items = { { "LoginProvider", "GitHub" } } |
| 89 | + }; |
| 90 | + |
| 91 | + return Challenge(properties, "GitHub"); |
| 92 | + } |
| 93 | + |
| 94 | + /// <summary> |
| 95 | + /// Handles the GitHub OAuth callback, creates/links the user, and redirects with a JWT token. |
| 96 | + /// </summary> |
| 97 | + [HttpGet("github/callback")] |
| 98 | + [EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)] |
| 99 | + public async Task<IActionResult> GitHubCallback([FromQuery] string? returnUrl = null) |
| 100 | + { |
| 101 | + if (!_gitHubOAuthSettings.IsConfigured) |
| 102 | + return NotFound(new ApiErrorResponse(ErrorCodes.NotFound, "GitHub OAuth is not configured")); |
| 103 | + |
| 104 | + var authenticateResult = await HttpContext.AuthenticateAsync("GitHub"); |
| 105 | + if (!authenticateResult.Succeeded || authenticateResult.Principal == null) |
| 106 | + { |
| 107 | + return Unauthorized(new ApiErrorResponse( |
| 108 | + ErrorCodes.AuthenticationFailed, |
| 109 | + "GitHub authentication failed")); |
| 110 | + } |
| 111 | + |
| 112 | + var claims = authenticateResult.Principal.Claims.ToList(); |
| 113 | + var providerUserId = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value; |
| 114 | + var username = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name)?.Value |
| 115 | + ?? claims.FirstOrDefault(c => c.Type == "urn:github:login")?.Value; |
| 116 | + var email = claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value; |
| 117 | + var displayName = claims.FirstOrDefault(c => c.Type == "urn:github:name")?.Value; |
| 118 | + var avatarUrl = claims.FirstOrDefault(c => c.Type == "urn:github:avatar")?.Value; |
| 119 | + |
| 120 | + if (string.IsNullOrWhiteSpace(providerUserId)) |
| 121 | + { |
| 122 | + return Unauthorized(new ApiErrorResponse( |
| 123 | + ErrorCodes.AuthenticationFailed, |
| 124 | + "GitHub did not return a user identifier")); |
| 125 | + } |
| 126 | + |
| 127 | + // GitHub may not return an email if user's email is private |
| 128 | + if (string.IsNullOrWhiteSpace(email)) |
| 129 | + email = $"{providerUserId}@users.noreply.github.com"; |
| 130 | + |
| 131 | + if (string.IsNullOrWhiteSpace(username)) |
| 132 | + username = $"github-user-{providerUserId}"; |
| 133 | + |
| 134 | + var dto = new ExternalLoginDto( |
| 135 | + Provider: "GitHub", |
| 136 | + ProviderUserId: providerUserId, |
| 137 | + Username: username, |
| 138 | + Email: email, |
| 139 | + DisplayName: displayName, |
| 140 | + AvatarUrl: avatarUrl); |
| 141 | + |
| 142 | + var result = await _authService.ExternalLoginAsync(dto); |
| 143 | + |
| 144 | + if (!result.IsSuccess) |
| 145 | + return result.ToErrorActionResult(); |
| 146 | + |
| 147 | + // Sign out the temporary cookie used during the OAuth handshake |
| 148 | + await HttpContext.SignOutAsync("GitHub"); |
| 149 | + |
| 150 | + // Security: Do NOT put the JWT in the URL. Use a short-lived, single-use |
| 151 | + // authorization code that the frontend exchanges via POST. |
| 152 | + var code = GenerateAuthCode(); |
| 153 | + _authCodes[code] = (result.Value, DateTimeOffset.UtcNow.AddSeconds(60)); |
| 154 | + CleanupExpiredCodes(); |
| 155 | + |
| 156 | + var safeReturnUrl = !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) |
| 157 | + ? returnUrl |
| 158 | + : "/"; |
| 159 | + |
| 160 | + var separator = safeReturnUrl.Contains('?') ? "&" : "?"; |
| 161 | + return Redirect($"{safeReturnUrl}{separator}oauth_code={Uri.EscapeDataString(code)}"); |
| 162 | + } |
| 163 | + |
| 164 | + /// <summary> |
| 165 | + /// Exchanges a short-lived OAuth authorization code for a JWT token. |
| 166 | + /// The code is single-use and expires after 60 seconds. |
| 167 | + /// </summary> |
| 168 | + [HttpPost("github/exchange")] |
| 169 | + [EnableRateLimiting(RateLimitingPolicyNames.AuthPerIp)] |
| 170 | + public IActionResult ExchangeCode([FromBody] ExchangeCodeRequest request) |
| 171 | + { |
| 172 | + if (string.IsNullOrWhiteSpace(request.Code)) |
| 173 | + return BadRequest(new ApiErrorResponse(ErrorCodes.ValidationError, "Code is required")); |
| 174 | + |
| 175 | + if (!_authCodes.TryRemove(request.Code, out var entry)) |
| 176 | + return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, "Invalid or expired code")); |
| 177 | + |
| 178 | + if (DateTimeOffset.UtcNow > entry.Expiry) |
| 179 | + return Unauthorized(new ApiErrorResponse(ErrorCodes.AuthenticationFailed, "Code has expired")); |
| 180 | + |
| 181 | + return Ok(entry.Result); |
| 182 | + } |
| 183 | + |
| 184 | + /// <summary> |
| 185 | + /// Returns whether GitHub OAuth login is available on this instance. |
| 186 | + /// </summary> |
| 187 | + [HttpGet("providers")] |
| 188 | + public IActionResult GetProviders() |
| 189 | + { |
| 190 | + return Ok(new |
| 191 | + { |
| 192 | + GitHub = _gitHubOAuthSettings.IsConfigured |
| 193 | + }); |
| 194 | + } |
| 195 | + |
| 196 | + private static string GenerateAuthCode() |
| 197 | + { |
| 198 | + var bytes = RandomNumberGenerator.GetBytes(32); |
| 199 | + return Convert.ToBase64String(bytes).Replace("+", "-").Replace("/", "_").TrimEnd('='); |
| 200 | + } |
| 201 | + |
| 202 | + private static void CleanupExpiredCodes() |
| 203 | + { |
| 204 | + var now = DateTimeOffset.UtcNow; |
| 205 | + foreach (var kvp in _authCodes) |
| 206 | + { |
| 207 | + if (now > kvp.Value.Expiry) |
| 208 | + _authCodes.TryRemove(kvp.Key, out _); |
| 209 | + } |
| 210 | + } |
59 | 211 | } |
0 commit comments