MessageUtil.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.ComIntegration
  5. {
  6. using System;
  7. using System.IdentityModel.Claims;
  8. using System.IdentityModel.Policy;
  9. using System.Security.Permissions;
  10. using System.Security.Principal;
  11. using System.ServiceModel;
  12. using System.ServiceModel.Channels;
  13. using System.ServiceModel.Security;
  14. using System.Transactions;
  15. using System.ServiceModel.Transactions;
  16. using System.ServiceModel.Diagnostics;
  17. using System.EnterpriseServices;
  18. static class MessageUtil
  19. {
  20. public static WindowsIdentity GetMessageIdentity(Message message)
  21. {
  22. WindowsIdentity callerIdentity = null;
  23. SecurityMessageProperty securityProp;
  24. securityProp = message.Properties.Security;
  25. if (securityProp != null)
  26. {
  27. ServiceSecurityContext context;
  28. context = securityProp.ServiceSecurityContext;
  29. if (context != null)
  30. {
  31. if (context.WindowsIdentity == null)
  32. {
  33. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.RequiresWindowsSecurity());
  34. }
  35. callerIdentity = context.WindowsIdentity;
  36. }
  37. }
  38. if ((callerIdentity == null) || (callerIdentity.IsAnonymous))
  39. {
  40. // No security, no identity, must be anonymous.
  41. callerIdentity = SecurityUtils.GetAnonymousIdentity();
  42. }
  43. return callerIdentity;
  44. }
  45. // The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
  46. /*
  47. [PermissionSet(SecurityAction.Demand, Unrestricted = true)] // because we call code from a non-APTCA assembly; transactions are not supported in partial trust, so customers should not be broken by this demand
  48. */
  49. public static Transaction GetMessageTransaction(Message message)
  50. {
  51. ServiceConfig serviceConfig = new ServiceConfig();
  52. serviceConfig.Transaction = TransactionOption.Disabled;
  53. ServiceDomain.Enter( serviceConfig );
  54. try
  55. {
  56. return TransactionMessageProperty.TryGetTransaction(message);
  57. }
  58. finally
  59. {
  60. ServiceDomain.Leave();
  61. }
  62. }
  63. }
  64. }