private async Task AcquireSamlSecurityTokenAsync()

in wwauth/Google.Solutions.WWAuth/Adapters/Adfs/AdfsWsTrustAdapter.cs [96:156]


        private async Task<GenericXmlSecurityToken> AcquireSamlSecurityTokenAsync(
            WSTrustChannelFactory factory)
        {
            //
            // Request a SAML 2.0 assertion (as opposed to SAML 1.1, which is
            // the default for WS-Trust).
            //
            var tokenRequest = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(this.RelyingPartyId),
                KeyType = KeyTypes.Bearer,
                TokenType = "urn:oasis:names:tc:SAML:2.0:assertion"
            };

            var channel = factory.CreateChannel();

            try
            {
                this.Logger.Info(
                    "Acquiring SAML assertion for {0} and relying party {1} using WS-Trust",
                    factory.Credentials.UserName,
                    factory.Endpoint.Address);

                return await Task.Factory.FromAsync(
                    channel.BeginIssue(tokenRequest, null, null),
                    ar => (GenericXmlSecurityToken)channel.EndIssue(ar, out var _));
            }
            catch (SecurityNegotiationException e)
            {
                throw new TokenAcquisitionException(
                    "Authentication failed. " +
                    "If AD FS is deployed behind a load balancer, verify that the " +
                    "token binding settings (ExtendedProtectionTokenCheck) are compatible " +
                    "with your load balancer setup.", e);
            }
            catch (FaultException e) when (
                e.Code != null &&
                e.Code.IsSenderFault &&
                e.Code.SubCode.Name == "InvalidScope")
            {
                throw new TokenAcquisitionException(
                    $"The relying party ID '{this.RelyingPartyId}' " +
                    "is invalid or does not exist", e);
            }
            catch (FaultException e) when (
                e.Code != null &&
                e.Code.IsSenderFault &&
                e.Code.SubCode.Name == "FailedAuthentication" &&
                factory.Credentials.UserName?.UserName != null)
            {
                throw new TokenAcquisitionException(
                    "Authentication failed, verify that the credentials " +
                    $"for {factory.Credentials.UserName.UserName} are correct", e);
            }
            catch (Exception e)
            {
                this.Logger.Error(e, "Acquiring assertion failed: {0}", e.Message);
                throw;
            }
        }