AuthDelegateImplementation.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Aip.Service.Aip.Models;
  2. using Microsoft.Identity.Client;
  3. using Microsoft.Identity.Client.Extensions.Msal;
  4. using Microsoft.InformationProtection;
  5. using System.Reflection;
  6. namespace Aip.Service.Aip;
  7. public class AuthDelegateImplementation : IAuthDelegate
  8. {
  9. private readonly Serilog.ILogger _log;
  10. public int LastErrNo { get; set; }
  11. public string LastErrMsg { get; set; }
  12. private readonly AipConfig _aipConfig;
  13. private readonly IConfidentialClientApplication _confidentialApp;
  14. // [Obsolete("Obsolete")] private TokenCache _tokenCache = new TokenCache();
  15. public AuthDelegateImplementation(Serilog.Core.Logger logger, AipConfig aipConfig)
  16. {
  17. _log = logger.ForContext<AuthDelegateImplementation>();
  18. _aipConfig = aipConfig;
  19. LastErrNo = 0;
  20. LastErrMsg = string.Empty;
  21. var storageProperties =
  22. new StorageCreationPropertiesBuilder(
  23. "AIPGateway.Cache",
  24. Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
  25. .Build();
  26. var cacheHelper = MsalCacheHelper.CreateAsync(storageProperties).GetAwaiter().GetResult();
  27. ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions()
  28. {
  29. ClientSecret = _aipConfig.SecretValue,
  30. ClientId = _aipConfig.ClientId,
  31. TenantId = _aipConfig.TenantId,
  32. RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient",
  33. Instance = "https://login.microsoftonline.com/"
  34. };
  35. _confidentialApp = ConfidentialClientApplicationBuilder
  36. .CreateWithApplicationOptions(options)
  37. .WithRedirectUri(options.RedirectUri)
  38. // .WithLegacyCacheCompatibility(false)
  39. // .WithExperimentalFeatures() // for PoP
  40. // .WithCacheOptions(CacheOptions.EnableSharedCacheOptions)
  41. .Build();
  42. cacheHelper.RegisterCache(_confidentialApp.UserTokenCache);
  43. }
  44. public void ResetError()
  45. {
  46. LastErrNo = 0;
  47. LastErrMsg = string.Empty;
  48. }
  49. private void SetError(int errNo, string errMsg1, string errMsg2 = "No Exception Message.")
  50. {
  51. LastErrNo = errNo;
  52. LastErrMsg = errMsg1 + "\r\n" + errMsg2;
  53. _log.Error("AuthDelegateImplementation::SetError ==> {0}, {1}, {2}", errNo, errMsg1, errMsg2);
  54. }
  55. public string AcquireToken(Identity identity, string authority, string resource, string claim)
  56. {
  57. return AcquireTokenByCertificate(identity, authority, resource, claim);
  58. }
  59. private string AcquireTokenByCertificate(Identity identity, string authority, string resource, string claims)
  60. {
  61. var scopes = new[] { resource[resource.Length - 1].Equals('/') ? $"{resource}.default" : $"{resource}/.default" };
  62. try
  63. {
  64. AuthenticationResult result;
  65. result = _confidentialApp.AcquireTokenForClient(scopes)
  66. .ExecuteAsync(CancellationToken.None)
  67. .ConfigureAwait(false)
  68. .GetAwaiter()
  69. .GetResult();
  70. return result.AccessToken;
  71. }
  72. catch (MsalUiRequiredException ex) when (ex.Message.Contains("AADSTS70011"))
  73. {
  74. SetError(1, "AcquireTokenByCertificate::AcquireTokenByCertificate, Scope provided is not supported.", ex.Message);
  75. }
  76. catch (Exception ex)
  77. {
  78. SetError(1, "AcquireTokenByCertificate::AcquireTokenByCertificate Failed.", ex.Message);
  79. }
  80. return "";
  81. }
  82. }