AuthDelegateImplementation.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Threading.Tasks;
  8. using Microsoft.Identity.Client;
  9. using Microsoft.InformationProtection;
  10. namespace AipGateway.AIP
  11. {
  12. public class AuthDelegateImplementation : IAuthDelegate
  13. {
  14. private static string _clientId = "";
  15. private static string thumbprint = "";
  16. private static bool doCertAuth = false;
  17. private static string _clientSecret = "";
  18. private ClaimsPrincipal _claimsPrincipal;
  19. public AuthDelegateImplementation(string clientId, string clientSecret, ClaimsPrincipal claimsPrincipal)
  20. {
  21. _clientId = clientId;
  22. _clientSecret = clientSecret;
  23. _claimsPrincipal = claimsPrincipal;
  24. }
  25. public string AcquireToken(Identity identity, string authority, string resource, string claim)
  26. {
  27. var authResult = Task.Run(async () => await GetAccessTokenOnBehalfOfUser(authority, resource));
  28. return authResult.Result;
  29. }
  30. public async Task<string> GetAccessTokenOnBehalfOfUser(string authority, string resource)
  31. {
  32. IConfidentialClientApplication _app;
  33. AuthenticationResult result;
  34. if (doCertAuth)
  35. {
  36. // Read X509 cert from local store and build ClientAssertionCertificate.
  37. X509Certificate2 cert = Utilities.ReadCertificateFromStore(thumbprint);
  38. // Create confidential client using certificate.
  39. _app = ConfidentialClientApplicationBuilder.Create(_clientId)
  40. .WithRedirectUri(resource)
  41. .WithAuthority(authority)
  42. .WithCertificate(cert)
  43. .Build();
  44. }
  45. else
  46. {
  47. // Create confidential client using client secret.
  48. _app = ConfidentialClientApplicationBuilder.Create(_clientId)
  49. .WithRedirectUri(resource)
  50. .WithAuthority(authority)
  51. .WithClientSecret(_clientSecret)
  52. .Build();
  53. }
  54. // Store user access token of authenticated user.
  55. var ci = (ClaimsIdentity)_claimsPrincipal.Identity;
  56. string userAccessToken = (string)ci.BootstrapContext;
  57. // Generate a user assertion with the UPN and access token.
  58. UserAssertion userAssertion = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer");
  59. // Append .default to the resource passed in to AcquireToken().
  60. List<string> scopes = new List<string>() { resource[resource.Length - 1].Equals('/') ? $"{resource}.default" : $"{resource}/.default" };
  61. result = await _app.AcquireTokenOnBehalfOf(scopes, userAssertion)
  62. .ExecuteAsync();
  63. // Return the token to the API caller
  64. return (result.AccessToken);
  65. }
  66. }
  67. }