FederatedSecurityTokenManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Globalization;
  7. using System.IdentityModel;
  8. using System.IdentityModel.Protocols.WSTrust;
  9. using System.IdentityModel.Selectors;
  10. using System.IdentityModel.Tokens;
  11. using System.ServiceModel.Description;
  12. using System.ServiceModel.Security.Tokens;
  13. using SR = System.ServiceModel.SR;
  14. namespace System.ServiceModel.Security
  15. {
  16. /// <summary>
  17. /// SecurityTokenManager that enables plugging custom tokens easily.
  18. /// The SecurityTokenManager provides methods to register custom token providers,
  19. /// serializers and authenticators. It can wrap another Token Managers and
  20. /// delegate token operation calls to it if required.
  21. /// </summary>
  22. /// <remarks>
  23. /// Framework use only - this is an implementation adapter class that is used to expose
  24. /// the Framework SecurityTokenHandlers to WCF.
  25. /// </remarks>
  26. sealed class FederatedSecurityTokenManager : ServiceCredentialsSecurityTokenManager
  27. {
  28. static string ListenUriProperty = "http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/ListenUri";
  29. ExceptionMapper _exceptionMapper;
  30. SecurityTokenResolver _defaultTokenResolver;
  31. SecurityTokenHandlerCollection _securityTokenHandlerCollection;
  32. object _syncObject = new object();
  33. ReadOnlyCollection<CookieTransform> _cookieTransforms;
  34. SessionSecurityTokenCache _tokenCache;
  35. /// <summary>
  36. /// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
  37. /// </summary>
  38. /// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
  39. /// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
  40. public FederatedSecurityTokenManager( ServiceCredentials parentCredentials )
  41. : base( parentCredentials )
  42. {
  43. if ( parentCredentials == null )
  44. {
  45. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials" );
  46. }
  47. if ( parentCredentials.IdentityConfiguration == null )
  48. {
  49. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials.IdentityConfiguration" );
  50. }
  51. _exceptionMapper = parentCredentials.ExceptionMapper;
  52. _securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;
  53. _tokenCache = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;
  54. _cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
  55. }
  56. /// <summary>
  57. /// Returns the list of SecurityTokenHandlers.
  58. /// </summary>
  59. public SecurityTokenHandlerCollection SecurityTokenHandlers
  60. {
  61. //
  62. //
  63. get { return _securityTokenHandlerCollection; }
  64. }
  65. /// <summary>
  66. /// Gets or sets the ExceptionMapper to be used when throwing exceptions.
  67. /// </summary>
  68. public ExceptionMapper ExceptionMapper
  69. {
  70. get
  71. {
  72. return _exceptionMapper;
  73. }
  74. set
  75. {
  76. if ( value == null )
  77. {
  78. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "value" );
  79. }
  80. _exceptionMapper = value;
  81. }
  82. }
  83. #region SecurityTokenManager Implementation
  84. /// <summary>
  85. /// Overriden from the base class. Creates the requested Token Authenticator.
  86. /// Looks up the list of Token Handlers registered with the token Manager
  87. /// based on the TokenType Uri in the SecurityTokenRequirement. If none is found,
  88. /// then the call is delegated to the inner Token Manager.
  89. /// </summary>
  90. /// <param name="tokenRequirement">Security Token Requirement for which the Authenticator should be created.</param>
  91. /// <param name="outOfBandTokenResolver">Token resolver that resolves any out-of-band tokens.</param>
  92. /// <returns>Instance of Security Token Authenticator.</returns>
  93. /// <exception cref="ArgumentNullException">'tokenRequirement' parameter is null.</exception>
  94. /// <exception cref="NotSupportedException">No Authenticator is registered for the given token type.</exception>
  95. public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
  96. {
  97. if ( tokenRequirement == null )
  98. {
  99. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
  100. }
  101. outOfBandTokenResolver = null;
  102. // Check for a registered authenticator
  103. SecurityTokenAuthenticator securityTokenAuthenticator = null;
  104. string tokenType = tokenRequirement.TokenType;
  105. //
  106. // When the TokenRequirement.TokenType is null, we treat this as a SAML issued token case. It may be SAML 1.1 or SAML 2.0.
  107. //
  108. if ( String.IsNullOrEmpty( tokenType ) )
  109. {
  110. return CreateSamlSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  111. }
  112. //
  113. // When the TokenType is set, build a token authenticator for the specified token type.
  114. //
  115. SecurityTokenHandler securityTokenHandler = _securityTokenHandlerCollection[tokenType];
  116. if ( ( securityTokenHandler != null ) && ( securityTokenHandler.CanValidateToken ) )
  117. {
  118. outOfBandTokenResolver = GetDefaultOutOfBandTokenResolver();
  119. if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.UserName ) )
  120. {
  121. UserNameSecurityTokenHandler upSecurityTokenHandler = securityTokenHandler as UserNameSecurityTokenHandler;
  122. if ( upSecurityTokenHandler == null )
  123. {
  124. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  125. new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( UserNameSecurityTokenHandler ) ) ) );
  126. }
  127. securityTokenAuthenticator = new WrappedUserNameSecurityTokenAuthenticator( upSecurityTokenHandler, _exceptionMapper );
  128. }
  129. else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Kerberos ) )
  130. {
  131. securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  132. }
  133. else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Rsa ) )
  134. {
  135. RsaSecurityTokenHandler rsaSecurityTokenHandler = securityTokenHandler as RsaSecurityTokenHandler;
  136. if ( rsaSecurityTokenHandler == null )
  137. {
  138. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  139. new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( RsaSecurityTokenHandler ) ) ) );
  140. }
  141. securityTokenAuthenticator = new WrappedRsaSecurityTokenAuthenticator( rsaSecurityTokenHandler, _exceptionMapper );
  142. }
  143. else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.X509Certificate ) )
  144. {
  145. X509SecurityTokenHandler x509SecurityTokenHandler = securityTokenHandler as X509SecurityTokenHandler;
  146. if ( x509SecurityTokenHandler == null )
  147. {
  148. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  149. new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( X509SecurityTokenHandler ) ) ) );
  150. }
  151. securityTokenAuthenticator = new WrappedX509SecurityTokenAuthenticator( x509SecurityTokenHandler, _exceptionMapper );
  152. }
  153. else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.SamlTokenProfile11 ) ||
  154. StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSamlTokenProfile11 ) )
  155. {
  156. SamlSecurityTokenHandler saml11SecurityTokenHandler = securityTokenHandler as SamlSecurityTokenHandler;
  157. if ( saml11SecurityTokenHandler == null )
  158. {
  159. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  160. new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( SamlSecurityTokenHandler ) ) ) );
  161. }
  162. if ( saml11SecurityTokenHandler.Configuration == null )
  163. {
  164. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
  165. }
  166. securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
  167. // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
  168. outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
  169. }
  170. else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Saml2TokenProfile11 ) ||
  171. StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSaml2TokenProfile11 ) )
  172. {
  173. Saml2SecurityTokenHandler saml2SecurityTokenHandler = securityTokenHandler as Saml2SecurityTokenHandler;
  174. if ( saml2SecurityTokenHandler == null )
  175. {
  176. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  177. new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( Saml2SecurityTokenHandler ) ) ) );
  178. }
  179. if ( saml2SecurityTokenHandler.Configuration == null )
  180. {
  181. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
  182. }
  183. securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
  184. // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
  185. outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
  186. }
  187. else if ( StringComparer.Ordinal.Equals( tokenType, ServiceModelSecurityTokenTypes.SecureConversation ) )
  188. {
  189. RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
  190. if ( tr == null )
  191. {
  192. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
  193. }
  194. securityTokenAuthenticator = SetupSecureConversationWrapper( tr, securityTokenHandler as SessionSecurityTokenHandler, out outOfBandTokenResolver );
  195. }
  196. else
  197. {
  198. securityTokenAuthenticator = new SecurityTokenAuthenticatorAdapter( securityTokenHandler, _exceptionMapper );
  199. }
  200. }
  201. else
  202. {
  203. if ( tokenType == ServiceModelSecurityTokenTypes.SecureConversation
  204. || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
  205. || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
  206. || tokenType == ServiceModelSecurityTokenTypes.SecurityContext
  207. || tokenType == ServiceModelSecurityTokenTypes.Spnego )
  208. {
  209. RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
  210. if ( tr == null )
  211. {
  212. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
  213. }
  214. securityTokenAuthenticator = SetupSecureConversationWrapper( tr, null, out outOfBandTokenResolver );
  215. }
  216. else
  217. {
  218. securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  219. }
  220. }
  221. return securityTokenAuthenticator;
  222. }
  223. /// <summary>
  224. /// Helper method to setup the WrappedSecureConversttion
  225. /// </summary>
  226. SecurityTokenAuthenticator SetupSecureConversationWrapper( RecipientServiceModelSecurityTokenRequirement tokenRequirement, SessionSecurityTokenHandler tokenHandler, out SecurityTokenResolver outOfBandTokenResolver )
  227. {
  228. // This code requires Orcas SP1 to compile.
  229. // WCF expects this securityTokenAuthenticator to support:
  230. // 1. IIssuanceSecurityTokenAuthenticator
  231. // 2. ICommunicationObject is needed for this to work right.
  232. // WCF opens a listener in this STA that handles the nego and uses an internal class for negotiating the
  233. // the bootstrap tokens. We want to handle ValidateToken to return our authorization policies and surface the bootstrap tokens.
  234. // when sp1 is installed, use this one.
  235. //SecurityTokenAuthenticator sta = base.CreateSecureConversationTokenAuthenticator( tokenRequirement as RecipientServiceModelSecurityTokenRequirement, _saveBootstrapTokensInSession, out outOfBandTokenResolver );
  236. // use this code if SP1 is not installed
  237. SecurityTokenAuthenticator sta = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  238. SessionSecurityTokenHandler sessionTokenHandler = tokenHandler;
  239. //
  240. // If there is no SCT handler here, create one.
  241. //
  242. if ( tokenHandler == null )
  243. {
  244. sessionTokenHandler = new SessionSecurityTokenHandler( _cookieTransforms, SessionSecurityTokenHandler.DefaultTokenLifetime );
  245. sessionTokenHandler.ContainingCollection = _securityTokenHandlerCollection;
  246. sessionTokenHandler.Configuration = _securityTokenHandlerCollection.Configuration;
  247. }
  248. if ( ServiceCredentials != null )
  249. {
  250. sessionTokenHandler.Configuration.MaxClockSkew = ServiceCredentials.IdentityConfiguration.MaxClockSkew;
  251. }
  252. SctClaimsHandler claimsHandler = new SctClaimsHandler(
  253. _securityTokenHandlerCollection,
  254. GetNormalizedEndpointId( tokenRequirement ) );
  255. WrappedSessionSecurityTokenAuthenticator wssta = new WrappedSessionSecurityTokenAuthenticator( sessionTokenHandler, sta,
  256. claimsHandler, _exceptionMapper );
  257. WrappedTokenCache wrappedTokenCache = new WrappedTokenCache( _tokenCache, claimsHandler);
  258. SetWrappedTokenCache( wrappedTokenCache, sta, wssta, claimsHandler );
  259. outOfBandTokenResolver = wrappedTokenCache;
  260. return wssta;
  261. }
  262. /// <summary>
  263. /// The purpose of this method is to set our WrappedTokenCache as the token cache for SCT's.
  264. /// And to set our OnIssuedToken callback when in cookie mode.
  265. /// We have to use reflection here as this is a private method.
  266. /// </summary>
  267. static void SetWrappedTokenCache(
  268. WrappedTokenCache wrappedTokenCache,
  269. SecurityTokenAuthenticator sta,
  270. WrappedSessionSecurityTokenAuthenticator wssta,
  271. SctClaimsHandler claimsHandler )
  272. {
  273. if ( sta is SecuritySessionSecurityTokenAuthenticator )
  274. {
  275. ( sta as SecuritySessionSecurityTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
  276. }
  277. else if ( sta is AcceleratedTokenAuthenticator )
  278. {
  279. ( sta as AcceleratedTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
  280. }
  281. else if ( sta is SpnegoTokenAuthenticator )
  282. {
  283. ( sta as SpnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
  284. }
  285. else if ( sta is TlsnegoTokenAuthenticator )
  286. {
  287. ( sta as TlsnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
  288. }
  289. // we need to special case this as the OnTokenIssued callback is not hooked up in the cookie mode case.
  290. IIssuanceSecurityTokenAuthenticator issuanceTokenAuthenticator = sta as IIssuanceSecurityTokenAuthenticator;
  291. if ( issuanceTokenAuthenticator != null )
  292. {
  293. issuanceTokenAuthenticator.IssuedSecurityTokenHandler = claimsHandler.OnTokenIssued;
  294. issuanceTokenAuthenticator.RenewedSecurityTokenHandler = claimsHandler.OnTokenRenewed;
  295. }
  296. }
  297. /// <summary>
  298. /// Overriden from the base class. Creates the requested Token Serializer.
  299. /// Returns a Security Token Serializer that is wraps the list of token
  300. /// hanlders registerd and also the serializers from the inner token manager.
  301. /// </summary>
  302. /// <param name="version">SecurityTokenVersion of the serializer to be created.</param>
  303. /// <returns>Instance of SecurityTokenSerializer.</returns>
  304. /// <exception cref="ArgumentNullException">Input parameter is null.</exception>
  305. public override SecurityTokenSerializer CreateSecurityTokenSerializer( SecurityTokenVersion version )
  306. {
  307. if ( version == null )
  308. {
  309. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "version" );
  310. }
  311. TrustVersion trustVersion = null;
  312. SecureConversationVersion scVersion = null;
  313. foreach ( string securitySpecification in version.GetSecuritySpecifications() )
  314. {
  315. if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrustFeb2005Constants.NamespaceURI ) )
  316. {
  317. trustVersion = TrustVersion.WSTrustFeb2005;
  318. }
  319. else if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrust13Constants.NamespaceURI ) )
  320. {
  321. trustVersion = TrustVersion.WSTrust13;
  322. }
  323. else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversationFeb2005Constants.Namespace ) )
  324. {
  325. scVersion = SecureConversationVersion.WSSecureConversationFeb2005;
  326. }
  327. else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversation13Constants.Namespace ) )
  328. {
  329. scVersion = SecureConversationVersion.WSSecureConversation13;
  330. }
  331. if ( trustVersion != null && scVersion != null )
  332. {
  333. break;
  334. }
  335. }
  336. if ( trustVersion == null )
  337. {
  338. trustVersion = TrustVersion.WSTrust13;
  339. }
  340. if ( scVersion == null )
  341. {
  342. scVersion = SecureConversationVersion.WSSecureConversation13;
  343. }
  344. WsSecurityTokenSerializerAdapter adapter = new WsSecurityTokenSerializerAdapter( _securityTokenHandlerCollection,
  345. GetSecurityVersion( version ), trustVersion, scVersion, false, this.ServiceCredentials.IssuedTokenAuthentication.SamlSerializer,
  346. this.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder,
  347. this.ServiceCredentials.SecureConversationAuthentication.SecurityContextClaimTypes );
  348. adapter.MapExceptionsToSoapFaults = true;
  349. adapter.ExceptionMapper = _exceptionMapper;
  350. return adapter;
  351. }
  352. /// <summary>
  353. /// The out-of-band token resolver to be used if the authenticator does
  354. /// not provide another.
  355. /// </summary>
  356. /// <remarks>By default this will create the resolver with the service certificate and
  357. /// know certificates collections specified in the service credentials when the STS is
  358. /// hosted inside WCF.</remarks>
  359. SecurityTokenResolver GetDefaultOutOfBandTokenResolver()
  360. {
  361. if ( _defaultTokenResolver == null )
  362. {
  363. lock ( _syncObject )
  364. {
  365. if ( _defaultTokenResolver == null )
  366. {
  367. //
  368. // Create default Out-Of-Band SecurityResolver.
  369. //
  370. List<SecurityToken> outOfBandTokens = new List<SecurityToken>();
  371. if ( base.ServiceCredentials.ServiceCertificate.Certificate != null )
  372. {
  373. outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.ServiceCertificate.Certificate ) );
  374. }
  375. if ( ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates != null ) && ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count > 0 ) )
  376. {
  377. for ( int i = 0; i < base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count; ++i )
  378. {
  379. outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates[i]));
  380. }
  381. }
  382. _defaultTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( outOfBandTokens.AsReadOnly(), false );
  383. }
  384. }
  385. }
  386. return _defaultTokenResolver;
  387. }
  388. /// <summary>
  389. /// There is a bug in WCF where the version obtained from the public SecurityTokenVersion strings is wrong.
  390. /// The internal MessageSecurityTokenVersion has the right version.
  391. /// </summary>
  392. internal static SecurityVersion GetSecurityVersion( SecurityTokenVersion tokenVersion )
  393. {
  394. if ( tokenVersion == null )
  395. {
  396. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenVersion" );
  397. }
  398. //
  399. // Workaround for WCF bug.
  400. // In .NET 3.5 WCF returns the wrong Token Specification. We need to reflect on the
  401. // internal code so we can access the SecurityVersion directly instead of depending
  402. // on the security specification.
  403. //
  404. if ( tokenVersion is MessageSecurityTokenVersion )
  405. {
  406. SecurityVersion sv = ( tokenVersion as MessageSecurityTokenVersion ).SecurityVersion;
  407. if ( sv != null )
  408. {
  409. return sv;
  410. }
  411. }
  412. else
  413. {
  414. if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity11Constants.Namespace ) )
  415. {
  416. return SecurityVersion.WSSecurity11;
  417. }
  418. else if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity10Constants.Namespace ) )
  419. {
  420. return SecurityVersion.WSSecurity10;
  421. }
  422. }
  423. return SecurityVersion.WSSecurity11;
  424. }
  425. #endregion // SecurityTokenManager Implementation
  426. /// <summary>
  427. /// This method creates the inner security token authenticator from the base class.
  428. /// The wrapped token cache is initialized with this authenticator.
  429. /// </summary>
  430. SecurityTokenAuthenticator CreateInnerSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
  431. {
  432. SecurityTokenAuthenticator securityTokenAuthenticator = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  433. SctClaimsHandler claimsHandler = new SctClaimsHandler(
  434. _securityTokenHandlerCollection,
  435. GetNormalizedEndpointId( tokenRequirement ) );
  436. SetWrappedTokenCache( new WrappedTokenCache( _tokenCache, claimsHandler ), securityTokenAuthenticator, null, claimsHandler );
  437. return securityTokenAuthenticator;
  438. }
  439. /// <summary>
  440. /// This method creates a SAML security token authenticator when token type is null.
  441. /// It wraps the SAML 1.1 and the SAML 2.0 token handlers that are configured.
  442. /// If no token handler was found, then the inner token manager is created.
  443. /// </summary>
  444. SecurityTokenAuthenticator CreateSamlSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
  445. {
  446. outOfBandTokenResolver = null;
  447. SecurityTokenAuthenticator securityTokenAuthenticator = null;
  448. SamlSecurityTokenHandler saml11SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.SamlTokenProfile11] as SamlSecurityTokenHandler;
  449. Saml2SecurityTokenHandler saml2SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.Saml2TokenProfile11] as Saml2SecurityTokenHandler;
  450. if ( saml11SecurityTokenHandler != null && saml11SecurityTokenHandler.Configuration == null )
  451. {
  452. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
  453. }
  454. if ( saml2SecurityTokenHandler != null && saml2SecurityTokenHandler.Configuration == null )
  455. {
  456. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
  457. }
  458. if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler != null )
  459. {
  460. //
  461. // Both SAML 1.1 and SAML 2.0 token handlers have been configured.
  462. //
  463. WrappedSaml11SecurityTokenAuthenticator wrappedSaml11SecurityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
  464. WrappedSaml2SecurityTokenAuthenticator wrappedSaml2SecurityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
  465. securityTokenAuthenticator = new WrappedSamlSecurityTokenAuthenticator( wrappedSaml11SecurityTokenAuthenticator, wrappedSaml2SecurityTokenAuthenticator );
  466. // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
  467. List<SecurityTokenResolver> resolvers = new List<SecurityTokenResolver>();
  468. resolvers.Add( saml11SecurityTokenHandler.Configuration.ServiceTokenResolver );
  469. resolvers.Add( saml2SecurityTokenHandler.Configuration.ServiceTokenResolver );
  470. outOfBandTokenResolver = new AggregateTokenResolver( resolvers );
  471. }
  472. else if ( saml11SecurityTokenHandler == null && saml2SecurityTokenHandler != null )
  473. {
  474. //
  475. // SAML 1.1 token handler is not present but SAML 2.0 is. Set the token type to SAML 2.0
  476. //
  477. securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
  478. // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
  479. outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
  480. }
  481. else if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler == null )
  482. {
  483. //
  484. // SAML 1.1 token handler is present but SAML 2.0 is not. Set the token type to SAML 1.1
  485. //
  486. securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
  487. // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
  488. outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
  489. }
  490. else
  491. {
  492. securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
  493. }
  494. return securityTokenAuthenticator;
  495. }
  496. /// <summary>
  497. /// Converts the ListenUri in the <see cref="SecurityTokenRequirement"/> to a normalized string.
  498. /// The method preserves the Uri scheme, port and absolute path and replaces the host name
  499. /// with the string 'NormalizedHostName'.
  500. /// </summary>
  501. /// <param name="tokenRequirement">The <see cref="SecurityTokenRequirement"/> which contains the 'ListenUri' property.</param>
  502. /// <returns>A string representing the Normalized URI string.</returns>
  503. public static string GetNormalizedEndpointId( SecurityTokenRequirement tokenRequirement )
  504. {
  505. if ( tokenRequirement == null )
  506. {
  507. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
  508. }
  509. Uri listenUri = null;
  510. if ( tokenRequirement.Properties.ContainsKey( ListenUriProperty ) )
  511. {
  512. listenUri = tokenRequirement.Properties[ListenUriProperty] as Uri;
  513. }
  514. if ( listenUri == null )
  515. {
  516. throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4287, tokenRequirement ) );
  517. }
  518. if ( listenUri.IsDefaultPort )
  519. {
  520. return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName{1}", listenUri.Scheme, listenUri.AbsolutePath );
  521. }
  522. else
  523. {
  524. return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName:{1}{2}", listenUri.Scheme, listenUri.Port, listenUri.AbsolutePath );
  525. }
  526. }
  527. }
  528. }