Example #1
0
        internal override async Task PreTokenRequest()
        {
            await base.PreTokenRequest().ConfigureAwait(false);

            if (this.PerformUserRealmDiscovery())
            {
                UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState).ConfigureAwait(false);

                PlatformPlugin.Logger.Information(this.CallState, string.Format("User with hash '{0}' detected as '{1}'", PlatformPlugin.CryptographyHelper.CreateSha256Hash(this.userCredential.UserName), userRealmResponse.AccountType));

                if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl))
                    {
                        throw new MsalException(MsalError.MissingFederationMetadataUrl);
                    }

                    WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState).ConfigureAwait(false);

                    PlatformPlugin.Logger.Information(this.CallState, string.Format("WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl));

                    WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState).ConfigureAwait(false);

                    PlatformPlugin.Logger.Information(this.CallState, string.Format("Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType));

                    // We assume that if the response token type is not SAML 1.1, it is SAML 2
                    this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer, this.userCredential.UserName);
                }
                else
                {
                    throw new MsalException(MsalError.UnsupportedUserType);
                }
            }
        }
Example #2
0
        public async Task CloudAudienceUrnNullTest()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);
            await context.Authenticator.UpdateFromTemplateAsync(null);

            UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId, null);

            WsTrustAddress address = new WsTrustAddress()
            {
                Uri     = new Uri("https://some/address/usernamemixed"),
                Version = WsTrustVersion.WsTrust13
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse.xml"))
                }
            });

            WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(address, new UserCredential(TestConstants.DefaultDisplayableId), null, null);

            VerifyCloudInstanceUrnResponse(userRealmResponse.CloudAudienceUrn, "urn:federation:MicrosoftOnline");
        }
Example #3
0
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    try
                    {
                        channel.Open();
                        Message reply = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        channel.Close();
                    }
                }
            }

            return(WSTrustUtilities.CreateGenericXmlSecurityToken(request, trustResponse, _requestSerializationContext, _securityAlgorithmSuite));
        }
Example #4
0
        public async Task WsTrustRequestGenericCloudUrnTest()
        {
            WsTrustAddress address = new WsTrustAddress()
            {
                Uri     = new Uri("https://some/address/usernamemixed"),
                Version = WsTrustVersion.WsTrust13
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse.xml"))
                }
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse.xml"))
                }
            });

            WsTrustResponse wstResponse = await WsTrustRequest.SendRequestAsync(address, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword), null, TestConstants.CloudAudienceUrn);

            Assert.IsNotNull(wstResponse.Token);

            wstResponse = await WsTrustRequest.SendRequestAsync(address, new UserCredential(TestConstants.DefaultDisplayableId), null, TestConstants.CloudAudienceUrn);

            Assert.IsNotNull(wstResponse.Token);
        }
        public async Task WsTrustRequestFailureTestAsync()
        {
            string uri      = "https://some/address/usernamemixed";
            var    endpoint = new WsTrustEndpoint(new Uri(uri), WsTrustVersion.WsTrust13);

            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddMockHandlerContentNotFound(HttpMethod.Post, url: uri);

                var requestContext = new RequestContext(harness.ServiceBundle, Guid.NewGuid());
                try
                {
                    var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");

                    WsTrustResponse wstResponse =
                        await harness.ServiceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(MsalError.FederatedServiceReturnedError, ex.ErrorCode);
                }
            }
        }
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    Message         reply   = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                    SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                    trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                    CacheSecurityTokenResponse(request, trustResponse);
                }
            }

            // Create GenericXmlSecurityToken
            // Assumes that token is first and Saml2SecurityToken.
            using (var stream = new MemoryStream())
            {
                RequestSecurityTokenResponse response = trustResponse.RequestSecurityTokenResponseCollection[0];

                // Get attached and unattached references
                GenericXmlSecurityKeyIdentifierClause internalSecurityKeyIdentifierClause = null;
                if (response.AttachedReference != null)
                {
                    internalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.AttachedReference);
                }

                GenericXmlSecurityKeyIdentifierClause externalSecurityKeyIdentifierClause = null;
                if (response.UnattachedReference != null)
                {
                    externalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.UnattachedReference);
                }

                // Get proof token
                IdentityModel.Tokens.SecurityToken proofToken = GetProofToken(request, response);

                // Get lifetime
                DateTime created = response.Lifetime?.Created ?? DateTime.UtcNow;
                DateTime expires = response.Lifetime?.Expires ?? created.AddDays(1);

                return(new GenericXmlSecurityToken(response.RequestedSecurityToken.TokenElement,
                                                   proofToken,
                                                   created,
                                                   expires,
                                                   internalSecurityKeyIdentifierClause,
                                                   externalSecurityKeyIdentifierClause,
                                                   null));
            }
        }
 private void CacheSecurityTokenResponse(WsTrustRequest request, WsTrustResponse response)
 {
     if (WSTrustTokenParameters.CacheIssuedTokens)
     {
         // If cached responses are stored in a shared cache in the future, that cache should be written
         // to here, possibly including serializing the WsTrustResponse if the cache stores byte[] (as
         // IDistributedCache does).
         CachedResponse = response;
     }
 }
Example #8
0
        public void TestCreateFromResponse_WhenInputContainsWhitespace_ShouldPreserveWhitespace()
        {
            string sample         = File.ReadAllText("WsTrustResponse.xml");
            string characteristic = "\n        <saml:Assertion";

            StringAssert.Contains(sample, characteristic);
            WsTrustResponse resp = WsTrustResponse.CreateFromResponse(
                new MemoryStream(Encoding.UTF8.GetBytes(sample)), WsTrustVersion.WsTrust2005);

            StringAssert.Contains(resp.Token, characteristic);
        }
Example #9
0
        public void TestCreateFromResponseDocument_WhenInputContainsWhitespace_ShouldPreserveWhitespace()
        {
            string sample         = File.ReadAllText("WsTrustResponse.xml");
            string characteristic = "\n        <saml:Assertion";

            StringAssert.Contains(sample, characteristic);
            WsTrustResponse resp = WsTrustResponse.CreateFromResponseDocument(
                XDocument.Parse(sample, LoadOptions.PreserveWhitespace), WsTrustVersion.WsTrust2005);

            StringAssert.Contains(resp.Token, characteristic);
        }
        public async Task WsTrustRequestTest()
        {
            var federatedSts = SetupStsService(StsType.AADFederatedWithADFS3);
            AuthenticationContext context = new AuthenticationContext(federatedSts.Authority, federatedSts.ValidateAuthority);
            await context.Authenticator.UpdateFromTemplateAsync(null);

            UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, federatedSts.ValidUserName, null);

            XDocument mexDocument = await FecthMexAsync(userRealmResponse.FederationMetadataUrl);

            Verify.IsNotNull(mexDocument);
            WsTrustAddress wsTrustAddress = MexParser.ExtractWsTrustAddressFromMex(mexDocument, UserAuthType.UsernamePassword, null);

            Verify.IsNotNull(wsTrustAddress);

            WsTrustResponse wstResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, new UserCredential(federatedSts.ValidUserName, federatedSts.ValidPassword), null);

            Verify.IsNotNull(wstResponse.Token);
            Verify.IsTrue(wstResponse.TokenType.Contains("SAML"));

            SecureString securePassword = new SecureString();

            foreach (var ch in federatedSts.ValidPassword)
            {
                securePassword.AppendChar(ch);
            }

            wstResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, new UserCredential(federatedSts.ValidUserName, securePassword), null);

            Verify.IsNotNull(wstResponse.Token);
            Verify.IsTrue(wstResponse.TokenType.Contains("SAML"));

            try
            {
                await WsTrustRequest.SendRequestAsync(new WsTrustAddress { Uri = new Uri(wsTrustAddress.Uri.AbsoluteUri + "x") },
                                                      new UserCredential(federatedSts.ValidUserName, federatedSts.ValidPassword), null);
            }
            catch (AdalException ex)
            {
                Verify.IsNotNull(ex.ErrorCode, AdalError.FederatedServiceReturnedError);
                Verify.IsNotNull(ex.InnerException);
            }

            try
            {
                await WsTrustRequest.SendRequestAsync(new WsTrustAddress { Uri = new Uri(wsTrustAddress.Uri.AbsoluteUri) }, new UserCredential(federatedSts.ValidUserName, "InvalidPassword"), null);
            }
            catch (AdalException ex)
            {
                Verify.IsNotNull(ex.ErrorCode, AdalError.FederatedServiceReturnedError);
                Verify.IsNotNull(ex.InnerException);
            }
        }
        protected override async Task PreTokenRequestAsync()
        {
            await base.PreTokenRequestAsync().ConfigureAwait(false);

            if (this.PerformUserRealmDiscovery())
            {
                UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState).ConfigureAwait(false);

                CallState.Logger.InformationPii(CallState, string.Format(CultureInfo.CurrentCulture,
                                                                         " User with user name '{0}' detected as '{1}'", userCredential.UserName,
                                                                         userRealmResponse.AccountType));

                if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl))
                    {
                        throw new AdalException(AdalError.MissingFederationMetadataUrl);
                    }

                    WsTrustAddress wsTrustAddress = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState).ConfigureAwait(false);

                    CallState.Logger.InformationPii(CallState,
                                                    string.Format(CultureInfo.CurrentCulture, " WS-Trust endpoint '{0}' fetched from MEX at '{1}'",
                                                                  wsTrustAddress.Uri, userRealmResponse.FederationMetadataUrl));

                    WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustAddress, this.userCredential, this.CallState, userRealmResponse.CloudAudienceUrn).ConfigureAwait(false);

                    var msg = string.Format(CultureInfo.CurrentCulture,
                                            " Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType);
                    CallState.Logger.Information(this.CallState, msg);
                    CallState.Logger.InformationPii(this.CallState, msg);

                    // We assume that if the response token type is not SAML 1.1, it is SAML 2
                    this.userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
                }
                else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // handle password grant flow for the managed user
                    if (this.userCredential.PasswordToCharArray() == null)
                    {
                        throw new AdalException(AdalError.PasswordRequiredForManagedUserError);
                    }
                }
                else
                {
                    throw new AdalException(AdalError.UnknownUserType);
                }
            }
        }
        public async Task CloudAudienceUrnTest()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);
            await context.Authenticator.UpdateFromTemplateAsync(null);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/"
                                                                                + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Federated\",\"domain_name\":\"microsoft.com\"," +
                                                "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" +
                                                "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," +
                                                "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" +
                                                ",\"cloud_audience_urn\":\"urn:federation:Blackforest\"" +
                                                ",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId,
                                                                                                                   CallState.Default);

            WsTrustAddress address = new WsTrustAddress()
            {
                Uri     = new Uri("https://some/address/usernamemixed"),
                Version = WsTrustVersion.WsTrust13
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://some/address/usernamemixed")
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse13.xml"))
                }
            });

            WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(address, new UserCredential(TestConstants.DefaultDisplayableId), null, userRealmResponse.CloudAudienceUrn);

            VerifyCloudInstanceUrnResponse("urn:federation:Blackforest", userRealmResponse.CloudAudienceUrn);

            // All mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
Example #13
0
        public async Task <WsTrustResponse> GetWsTrustResponseAsync(
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            CancellationToken cancellationToken)
        {
            string wsTrustRequestMessage;
            var    authorizationType = _authenticationParameters.AuthorizationType;

            switch (authorizationType)
            {
            case AuthorizationType.WindowsIntegratedAuth:
                wsTrustRequestMessage = endpoint.BuildTokenRequestMessageWia(cloudAudienceUrn);
                break;

            case AuthorizationType.UsernamePassword:
                wsTrustRequestMessage = endpoint.BuildTokenRequestMessageUsernamePassword(
                    cloudAudienceUrn,
                    _authenticationParameters.UserName,
                    _authenticationParameters.Password);
                break;

            default:
                throw new InvalidOperationException();
            }

            string soapAction = endpoint.Version == WsTrustVersion.WsTrust2005
                                    ? WsTrustMexDocument.Trust2005Spec
                                    : WsTrustMexDocument.Trust13Spec;

            var requestHeaders = new Dictionary <string, string>
            {
                ["SOAPAction"]  = soapAction,
                ["ContentType"] = "application/soap+xml"
            };

            HttpContent body = new StringContent(wsTrustRequestMessage, Encoding.UTF8, requestHeaders["ContentType"]);

            var response = await _httpManager.PostAsync(endpoint.Uri, requestHeaders, body, cancellationToken)
                           .ConfigureAwait(false);

            return(WsTrustResponse.Create(response.StatusCode, response.ResponseData));
        }
Example #14
0
        public async Task WsTrustRequestGenericCloudUrnTestAsync()
        {
            HttpMessageHandlerFactory.InitializeMockProvider();

            string URI = "https://some/address/usernamemixed";

            WsTrustAddress address = new WsTrustAddress()
            {
                Uri     = new Uri(URI),
                Version = WsTrustVersion.WsTrust13
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(URI)
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse13.xml"))
                }
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(URI)
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("WsTrustResponse13.xml"))
                }
            });

            WsTrustResponse wstResponse = await WsTrustRequest.SendRequestAsync(address, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword), null, TestConstants.CloudAudienceUrn).ConfigureAwait(false);

            Assert.IsNotNull(wstResponse.Token);

            wstResponse = await WsTrustRequest.SendRequestAsync(address, new UserCredential(TestConstants.DefaultDisplayableId), null, TestConstants.CloudAudienceUrn).ConfigureAwait(false);

            Assert.IsNotNull(wstResponse.Token);

            // All mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
        public async Task WsTrustRequestParseErrorTestAsync()
        {
            const string body            = "Non-Parsable";
            const string uri             = "https://some/address/usernamemixed";
            string       expectedMessage = string.Format(CultureInfo.CurrentCulture, MsalErrorMessage.ParsingWsTrustResponseFailedErrorTemplate, uri, body);

            var endpoint = new WsTrustEndpoint(new Uri(uri), WsTrustVersion.WsTrust13);

            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedUrl     = uri,
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(body)
                    }
                });

                var requestContext = new RequestContext(harness.ServiceBundle, Guid.NewGuid());
                try
                {
                    var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");

                    WsTrustResponse wstResponse =
                        await harness.ServiceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(MsalError.ParsingWsTrustResponseFailed, ex.ErrorCode);
                    Assert.AreEqual(ex.Message, expectedMessage);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Sends a <see cref="WsTrustRequest"/> to a STS to obtain a <see cref="WCFSecurityToken"/>.
        /// </summary>
        /// <param name="trustRequest">The <see cref="WsTrustRequest" /> sent to the STS.</param>
        /// <returns>A <see cref="WCFSecurityToken" /> issued by the STS.</returns>
        public async virtual Task <WCFSecurityToken> IssueAsync(WsTrustRequest trustRequest)
        {
            _ = trustRequest ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(trustRequest));

            Message requestMessage = CreateRequest(trustRequest);
            Message response       = await Task.Factory.FromAsync(RequestChannel.BeginRequest, RequestChannel.EndRequest, requestMessage, null, TaskCreationOptions.None).ConfigureAwait(false);

            if (response.IsFault)
            {
                MessageFault fault = MessageFault.CreateFault(response, FaultMaxBufferSize);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultException.CreateFault(fault, response.Headers?.Action));
            }

            WsTrustResponse  trustResponse = TrustSerializer.ReadResponse(response.GetReaderAtBodyContents());
            WCFSecurityToken token         = WSTrustUtilities.CreateGenericXmlSecurityToken(trustRequest, trustResponse, GetSerializationContext(trustRequest), null);

            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToGetToken, string.IsNullOrEmpty(Address) ? ToString() : Address)));
            }

            return(token);
        }
        private async Task <SecurityToken> GetTokenAsyncCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    await Task.Factory.FromAsync(channel.BeginOpen, channel.EndOpen, null, TaskCreationOptions.None);

                    try
                    {
                        Message requestMessage = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader);
                        Message reply          = await Task.Factory.FromAsync(channel.BeginRequest, channel.EndRequest, requestMessage, null, TaskCreationOptions.None);

                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        await Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, null, TaskCreationOptions.None);
                    }
                }
            }

            return(CreateGenericXmlSecurityToken(request, trustResponse));
        }
        private SecurityToken CreateGenericXmlSecurityToken(WsTrustRequest request, WsTrustResponse trustResponse)
        {
            // Create GenericXmlSecurityToken
            // Assumes that token is first and Saml2SecurityToken.
            RequestSecurityTokenResponse response = trustResponse.RequestSecurityTokenResponseCollection[0];

            // Get attached and unattached references
            GenericXmlSecurityKeyIdentifierClause internalSecurityKeyIdentifierClause = null;

            if (response.AttachedReference != null)
            {
                internalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.AttachedReference);
            }

            GenericXmlSecurityKeyIdentifierClause externalSecurityKeyIdentifierClause = null;

            if (response.UnattachedReference != null)
            {
                externalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.UnattachedReference);
            }

            // Get proof token
            IdentityModel.Tokens.SecurityToken proofToken = GetProofToken(request, response);

            // Get lifetime
            DateTime created = response.Lifetime?.Created ?? DateTime.UtcNow;
            DateTime expires = response.Lifetime?.Expires ?? created.AddDays(1);

            return(new GenericXmlSecurityToken(response.RequestedSecurityToken.TokenElement,
                                               proofToken,
                                               created,
                                               expires,
                                               internalSecurityKeyIdentifierClause,
                                               externalSecurityKeyIdentifierClause,
                                               null));
        }
Example #19
0
 /// <summary>
 /// Gets all <see cref="SecurityToken"/>s that are in the <paramref name="response"/>.
 /// </summary>
 /// <param name="response">An <see cref="WsTrustResponse"/> instance.</param>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="SecurityToken"/>.</returns>
 public static IEnumerable <SecurityToken> GetRequestedSecurityTokens(this WsTrustResponse response)
 => response?.RequestSecurityTokenResponseCollection?.Select(r => r.RequestedSecurityToken?.SecurityToken) ?? Enumerable.Empty <SecurityToken>();
Example #20
0
 /// <summary>
 /// Gets all security token <see cref="XmlElement"/>s that are in the <paramref name="response"/>.
 /// </summary>
 /// <param name="response">An <see cref="WsTrustResponse"/> instance.</param>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="XmlElement"/>.</returns>
 public static IEnumerable <XmlElement> GetRequestedSecurityTokenElements(this WsTrustResponse response)
 => response?.RequestSecurityTokenResponseCollection?.Select(r => r.RequestedSecurityToken?.TokenElement) ?? Enumerable.Empty <XmlElement>();
Example #21
0
 /// <summary>
 /// Gets a single security token <see cref="XmlElement"/> that is in the <paramref name="response"/>.
 /// <para>If more than one security token is contained withing the <paramref name="response"/>, an exception will be thrown.</para>
 /// </summary>
 /// <param name="response">An <see cref="WsTrustResponse"/> instance.</param>
 /// <returns>A <see cref="XmlElement"/> instance.</returns>
 public static XmlElement GetRequestedSecurityTokenElement(this WsTrustResponse response)
 => response.GetRequestedSecurityTokenElements().Single();
Example #22
0
 /// <summary>
 /// Gets a single <see cref="SecurityToken"/> that is in the <paramref name="response"/>.
 /// <para>If more than one <see cref="SecurityToken"/> is contained withing the <paramref name="response"/>, an exception will be thrown.</para>
 /// </summary>
 /// <param name="response">An <see cref="WsTrustResponse"/> instance.</param>
 /// <returns>A <see cref="SecurityToken"/> instance.</returns>
 public static SecurityToken GetRequestedSecurityToken(this WsTrustResponse response)
 => response.GetRequestedSecurityTokens().Single();
Example #23
0
        public void TestConstructor_OK_NullResponse()
        {
            var response = WsTrustResponse.Create(HttpStatusCode.OK, null);

            Assert.Fail();
        }