|
| 1 | +using Microsoft.Extensions.Configuration; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Microsoft.Identity.Client; |
| 4 | + |
| 5 | +namespace SentenceStudio.Services; |
| 6 | + |
| 7 | +public class MsalAuthService : IAuthService |
| 8 | +{ |
| 9 | + private readonly string[] _defaultScopes; |
| 10 | + private readonly IPublicClientApplication _pca; |
| 11 | + private readonly ILogger<MsalAuthService> _logger; |
| 12 | + private IAccount? _cachedAccount; |
| 13 | + |
| 14 | + public bool IsSignedIn => _cachedAccount is not null; |
| 15 | + public string? UserName => _cachedAccount?.Username; |
| 16 | + |
| 17 | + public MsalAuthService(IConfiguration configuration, ILogger<MsalAuthService> logger) |
| 18 | + { |
| 19 | + _logger = logger; |
| 20 | + |
| 21 | + var tenantId = configuration["AzureAd:TenantId"] |
| 22 | + ?? throw new InvalidOperationException("AzureAd:TenantId must be configured."); |
| 23 | + var clientId = configuration["AzureAd:ClientId"] |
| 24 | + ?? throw new InvalidOperationException("AzureAd:ClientId must be configured."); |
| 25 | + var redirectUri = configuration["AzureAd:RedirectUri"] |
| 26 | + ?? $"msal{clientId}://auth"; |
| 27 | + |
| 28 | + _defaultScopes = configuration.GetSection("AzureAd:Scopes").Get<string[]>() |
| 29 | + ?? throw new InvalidOperationException( |
| 30 | + "AzureAd:Scopes must be configured. Add an array of API scopes to appsettings.json or user-secrets."); |
| 31 | + |
| 32 | + _pca = PublicClientApplicationBuilder |
| 33 | + .Create(clientId) |
| 34 | + .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) |
| 35 | + .WithRedirectUri(redirectUri) |
| 36 | + .Build(); |
| 37 | + } |
| 38 | + |
| 39 | + public async Task<AuthenticationResult?> SignInAsync() |
| 40 | + { |
| 41 | + try |
| 42 | + { |
| 43 | + var result = await AcquireTokenAsync(_defaultScopes); |
| 44 | + if (result is not null) |
| 45 | + { |
| 46 | + _cachedAccount = result.Account; |
| 47 | + _logger.LogInformation("Signed in as {User}", result.Account.Username); |
| 48 | + } |
| 49 | + return result; |
| 50 | + } |
| 51 | + catch (Exception ex) |
| 52 | + { |
| 53 | + _logger.LogError(ex, "Sign-in failed"); |
| 54 | + return null; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public async Task SignOutAsync() |
| 59 | + { |
| 60 | + try |
| 61 | + { |
| 62 | + var accounts = await _pca.GetAccountsAsync(); |
| 63 | + foreach (var account in accounts) |
| 64 | + { |
| 65 | + await _pca.RemoveAsync(account); |
| 66 | + } |
| 67 | + _cachedAccount = null; |
| 68 | + _logger.LogInformation("Signed out"); |
| 69 | + } |
| 70 | + catch (Exception ex) |
| 71 | + { |
| 72 | + _logger.LogError(ex, "Sign-out failed"); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + public async Task<string?> GetAccessTokenAsync(string[] scopes) |
| 77 | + { |
| 78 | + try |
| 79 | + { |
| 80 | + var result = await AcquireTokenAsync(scopes); |
| 81 | + return result?.AccessToken; |
| 82 | + } |
| 83 | + catch (Exception ex) |
| 84 | + { |
| 85 | + _logger.LogWarning(ex, "Failed to acquire access token"); |
| 86 | + return null; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + private async Task<AuthenticationResult?> AcquireTokenAsync(string[] scopes) |
| 91 | + { |
| 92 | + // Try silent acquisition first |
| 93 | + var accounts = await _pca.GetAccountsAsync(); |
| 94 | + var account = _cachedAccount ?? accounts.FirstOrDefault(); |
| 95 | + |
| 96 | + if (account is not null) |
| 97 | + { |
| 98 | + try |
| 99 | + { |
| 100 | + var result = await _pca.AcquireTokenSilent(scopes, account).ExecuteAsync(); |
| 101 | + _cachedAccount = result.Account; |
| 102 | + return result; |
| 103 | + } |
| 104 | + catch (MsalUiRequiredException) |
| 105 | + { |
| 106 | + _logger.LogDebug("Silent token acquisition failed, falling back to interactive"); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + // Fall back to interactive (system browser with PKCE) |
| 111 | + try |
| 112 | + { |
| 113 | + var result = await _pca.AcquireTokenInteractive(scopes) |
| 114 | + .WithUseEmbeddedWebView(false) |
| 115 | + .ExecuteAsync(); |
| 116 | + _cachedAccount = result.Account; |
| 117 | + return result; |
| 118 | + } |
| 119 | + catch (MsalClientException ex) when (ex.ErrorCode == MsalError.AuthenticationCanceledError) |
| 120 | + { |
| 121 | + _logger.LogInformation("User cancelled authentication"); |
| 122 | + return null; |
| 123 | + } |
| 124 | + } |
| 125 | +} |
0 commit comments