internal static Uri ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType)
        {
            Uri url;

            try
            {
                Dictionary <string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary <string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random    random = new Random();
                MexPolicy policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();
                if (policy != null)
                {
                    url = policy.Url;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    throw new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument));
                }
                else
                {
                    throw new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument);
                }
            }
            catch (XmlException ex)
            {
                throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return(url);
        }
        internal static Uri ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
        {
            Uri url;

            try
            {
                Dictionary<string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary<string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random random = new Random();
                MexPolicy policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();
                if (policy != null)
                {
                    url = policy.Url;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    throw new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument));
                }
                else
                {
                    throw new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument);
                }
            }
            catch (XmlException ex)
            {
                throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return url;
        }
Ejemplo n.º 3
0
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            string username,
            SecureString securePassword)
        {
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                username,
                new string(securePassword.PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsTrustResponseFailed,
                          ex.Message,
                          ex);
            }
        }
Ejemplo n.º 4
0
        public void AddUser(string name, string password, UserAuthType type)
        {
            try
            {
                name = name.ToLower(); //only lower case usernames are allowed

                User user = SecurityFramework.AddNewUser(name, password, type);
                if (_Users != null)
                {
                    if (string.IsNullOrEmpty(UsernameFilter))
                    {
                        UserInfo u = new UserInfo(user, SecurityFramework.Groups);
                        if (_Users.Count(ui => ui.User.Account == u.User.Account) > 0)
                        {
                            MessageBox.Show(String.Format("The given username '{0}' already exists.", u.User.Account),
                                            "Execution was aborted", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            _Users.Add(new UserInfo(user, SecurityFramework.Groups));
                        }
                    }
                    else if (user.Account.Contains(UsernameFilter))
                    {
                        _Users.Add(new UserInfo(user, SecurityFramework.Groups));
                        (MainWindow as MainWindow).ListBoxUsers.GetBindingExpression(System.Windows.Controls.ListBox.ItemsSourceProperty).UpdateTarget();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            string username,
            SecureString securePassword)
        {
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                username,
                new string(securePassword.PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsTrustResponseFailed,
                          "There was an error parsing WS-Trust response from the endpoint. This may occur if there is an issue with your ADFS configuration."
                          + " See https://aka.ms/msal-net-iwa-troubleshooting for more details. Error Message: " + ex.Message,
                          ex);
            }
        }
Ejemplo n.º 6
0
 internal ExistingUser(
     string userName,
     string externalId,
     string email,
     string familyName,
     string givenName,
     bool active,
     UserAuthType authType,
     UserType userType,
     string role,
     string idpUserId,
     string userPrincipalName,
     long id,
     bool locked)
 {
     UserName          = userName;
     ExternalId        = externalId;
     Email             = email;
     FamilyName        = familyName;
     GivenName         = givenName;
     Active            = active;
     AuthType          = authType;
     UserType          = userType;
     Role              = role;
     IdpUserId         = idpUserId;
     UserPrincipalName = userPrincipalName;
     Id     = id;
     Locked = locked;
 }
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            IUsernameInput usernameInput)
        {
            // TODO: need to clean up the casting to UsernamePasswordInput as well as removing the PasswordToCharArray
            // since we're putting the strings onto the managed heap anyway.
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                usernameInput.UserName,
                new string(((UsernamePasswordInput)usernameInput).PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw MsalExceptionFactory.GetClientException(
                          CoreErrorCodes.ParsingWsTrustResponseFailed,
                          ex.Message,
                          ex);
            }
        }
Ejemplo n.º 8
0
        public void UpdateUser(int userid, string name, string password, UserAuthType typ)
        {
            using (NpgsqlConnection conn = PostgreSQLConn.CreateConnection(_ConnectionString))
            {
                using (NpgsqlCommand cmd = conn.CreateCommand())
                {
                    string sCommand = "UPDATE \"UserProfiles\" ";
                    sCommand = sCommand + " SET username='******',";
                    if (typ == UserAuthType.ListAuthentication)
                    {
                        sCommand = sCommand + " password='',";
                    }
                    else
                    {
                        sCommand = sCommand + " password=md5('" + password + "'),";
                    }
                    sCommand        = sCommand + " user_type='" + typ.ToString() + "'";
                    sCommand        = sCommand + " WHERE id=" + userid;
                    cmd.CommandText = sCommand;

                    cmd.ExecuteNonQuery();
                }
            }
            Refresh();
        }
        public static async Task <WsTrustAddress> FetchWsTrustAddressFromMexAsync(string federationMetadataUrl,
                                                                                  UserAuthType userAuthType, CallState callState)
        {
            XDocument mexDocument = await FetchMexAsync(federationMetadataUrl, callState);

            return(ExtractWsTrustAddressFromMex(mexDocument, userAuthType, callState));
        }
Ejemplo n.º 10
0
 public Employee(int clientIdNumber, string contactNameber, string name, string lastName, UserAuthType userAuthType)
 {
     ClientIdNumber             = clientIdNumber;
     ContactNameber             = contactNameber;
     Name                       = name;
     LastName                   = lastName;
     UserAuthType               = userAuthType;
     NumberOfLineCustomersAdded = 0;
 }
        private WsTrustEndpoint GetWsTrustEndpoint(UserAuthType userAuthType)
        {
            MexPolicy policy = SelectPolicy(userAuthType);

            if (policy == null)
            {
                return(null);
            }

            return(new WsTrustEndpoint(policy.Url, policy.Version));
        }
Ejemplo n.º 12
0
 private void SetUserAuthInfo(HttpRequestBuilder builder, UserAuthType userAuthType, string userAuthInfo)
 {
     if (userAuthType == UserAuthType.BearerToken)
     {
         builder.AddBearerToken(userAuthInfo);
     }
     else if (userAuthType == UserAuthType.BasicAuth)
     {
         builder.AddBasicAuthUser(userAuthInfo);
     }
 }
Ejemplo n.º 13
0
        public async Task <HttpResponseMessage> Delete(
            string requestUri, UserAuthType userAuthType, string userAuthInfo)
        {
            var builder = new HttpRequestBuilder()
                          .AddMethod(HttpMethod.Delete)
                          .AddRequestUri(requestUri);

            SetUserAuthInfo(builder, userAuthType, userAuthInfo);

            return(await builder.SendAsync());
        }
Ejemplo n.º 14
0
        public async Task <HttpResponseMessage> Patch(
            string requestUri, object value, UserAuthType userAuthType, string userAuthInfo)
        {
            var builder = new HttpRequestBuilder()
                          .AddMethod(new HttpMethod("PATCH"))
                          .AddRequestUri(requestUri)
                          .AddContent(new PatchContent(value));

            SetUserAuthInfo(builder, userAuthType, userAuthInfo);

            return(await builder.SendAsync());
        }
Ejemplo n.º 15
0
        public async Task <HttpResponseMessage> Get(string requestUri, UserAuthType userAuthType, string userAuthInfo, Dictionary <string, string> customHeaders = null)
        {
            var builder = new HttpRequestBuilder()
                          .AddMethod(HttpMethod.Get)
                          .AddRequestUri(requestUri);

            SetUserAuthInfo(builder, userAuthType, userAuthInfo);

            SetHeaderInfo(builder, customHeaders);

            return(await builder.SendAsync());
        }
 private MexPolicy SelectPolicy(UserAuthType userAuthType)
 {
     //try ws-trust 1.3 first
     return(_policies
            .Values
            .Where(p => p.Url != null && p.AuthType == userAuthType && p.Version == WsTrustVersion.WsTrust13)
            .FirstOrDefault() ??
            _policies
            .Values
            .Where(p => p.Url != null && p.AuthType == userAuthType)
            .FirstOrDefault());
 }
Ejemplo n.º 17
0
        public User _AddUser(string account, string password, UserAuthType type)
        {
            int userid = Adapters.UserProfilesAdapter.AddUser(account, password, type);

            Reset();
            foreach (User user in _Users)
            {
                if (user.Id == userid.ToString())
                {
                    return(user);
                }
            }
            return(null);
        }
Ejemplo n.º 18
0
        string MapAuthType(UserAuthType authType)
        {
            switch (authType)
            {
            case UserAuthType.SAML_SSO:
                return("sso");

            case UserAuthType.Internal_Egnyte:
                return("egnyte");

            default:
                return("ad");
            }
        }
        private void AddPolicy(XElement policy, UserAuthType policyAuthType)
        {
            XElement binding = policy.Descendants(XmlNamespace.Sp + "TransportBinding").FirstOrDefault()
                               ?? policy.Descendants(XmlNamespace.Sp2005 + "TransportBinding").FirstOrDefault();

            if (binding != null)
            {
                XAttribute id = policy.Attribute(XmlNamespace.Wsu + "Id");
                if (id != null)
                {
                    _policies.Add("#" + id.Value, new MexPolicy {
                        Id = id.Value, AuthType = policyAuthType
                    });
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <WsTrustResponse> PerformWsTrustMexExchangeAsync(
            string federationMetadataUrl, string cloudAudienceUrn, UserAuthType userAuthType, string username, SecureString password, string federationMetadataFilename)
        {
            MexDocument mexDocument;

            try
            {
                mexDocument = await _serviceBundle.WsTrustWebRequestManager.GetMexDocumentAsync(
                    federationMetadataUrl,
                    _requestContext,
                    federationMetadataFilename).ConfigureAwait(false);
            }
            catch (XmlException ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsMetadataExchangeFailed,
                          MsalErrorMessage.ParsingMetadataDocumentFailed,
                          ex);
            }

            WsTrustEndpoint wsTrustEndpoint = userAuthType == UserAuthType.IntegratedAuth
                ? mexDocument.GetWsTrustWindowsTransportEndpoint()
                : mexDocument.GetWsTrustUsernamePasswordEndpoint();

            if (wsTrustEndpoint == null)
            {
                throw new MsalClientException(
                          MsalError.WsTrustEndpointNotFoundInMetadataDocument,
                          MsalErrorMessage.WsTrustEndpointNotFoundInMetadataDocument);
            }

            _requestContext.Logger.InfoPii(
                string.Format(CultureInfo.InvariantCulture, "WS-Trust endpoint '{0}' being used from MEX at '{1}'", wsTrustEndpoint.Uri, federationMetadataUrl),
                "Fetched and parsed MEX. ");

            WsTrustResponse wsTrustResponse = await GetWsTrustResponseAsync(
                userAuthType,
                cloudAudienceUrn,
                wsTrustEndpoint,
                username,
                password).ConfigureAwait(false);

            _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");

            return(wsTrustResponse);
        }
Ejemplo n.º 21
0
        public int AddUser(string account, string password, UserAuthType type)
        {
            using (NpgsqlConnection conn = PostgreSQLConn.CreateConnection(_ConnectionString))
            {
                using (NpgsqlCommand cmd = conn.CreateCommand())
                {
                    //CFI: Do not use CommandType.StoredProcedure as this will convert \ -> \\
                    cmd.CommandText = "SELECT * FROM \"InsertUserProfile\"(:p_username, :p_password, :p_local_directory_id, :p_user_type)";
                    cmd.Parameters.Add("p_username", account);
                    cmd.Parameters.Add("p_password", password);
                    cmd.Parameters.Add("p_local_directory_id", string.Empty);
                    cmd.Parameters.Add("p_user_type", type.ToString());
                    object result = cmd.ExecuteScalar();

                    if (result == null || result is System.DBNull)
                    {
                        return(-1);
                    }
                    Refresh();

                    return(Convert.ToInt32(result));
                }
            }
        }
        private static void AddPolicy(IDictionary<string, MexPolicy> policies, XElement policy, UserAuthType policyAuthType)
        {
            XElement binding = policy.Descendants(XmlNamespace.Sp + "TransportBinding").FirstOrDefault()
                          ?? policy.Descendants(XmlNamespace.Sp2005 + "TransportBinding").FirstOrDefault();

            if (binding != null)
            {
                XAttribute id = policy.Attribute(XmlNamespace.Wsu + "Id");
                if (id != null)
                {
                    policies.Add("#" + id.Value, new MexPolicy { Id = id.Value, AuthType = policyAuthType });
                }
            }
        }
 public WeedHackersAuthAttribute(UserAuthType authType)
 {
     _authType = authType;
 }
 internal UserCredential(string userName, UserAuthType userAuthType)
 {
     this.UserName     = userName;
     this.UserAuthType = userAuthType;
 }
Ejemplo n.º 25
0
        public void AddUser(string name, string password, UserAuthType type)
        {
            try
            {
                name = name.ToLower(); //only lower case usernames are allowed

                User user = SecurityFramework.AddNewUser(name, password, type);
                if (_Users != null)
                {
                    if (string.IsNullOrEmpty(UsernameFilter))
                    {
                        UserInfo u = new UserInfo(user, SecurityFramework.Groups);
                        if (_Users.Count(ui => ui.User.Account == u.User.Account) > 0)
                        {
                            MessageBox.Show(String.Format("The given username '{0}' already exists.", u.User.Account),
                                "Execution was aborted", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            _Users.Add(new UserInfo(user, SecurityFramework.Groups));
                        }
                    }
                    else if (user.Account.Contains(UsernameFilter))
                    {
                        _Users.Add(new UserInfo(user, SecurityFramework.Groups));
                        (MainWindow as MainWindow).ListBoxUsers.GetBindingExpression(System.Windows.Controls.ListBox.ItemsSourceProperty).UpdateTarget();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 /// <summary>
 /// Adds a user.
 /// </summary>
 /// <param name="account">The account.</param>
 /// <param name="password">The password.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 /// <remarks>
 /// Documented by AAB, 27.02.2009.
 /// </remarks>
 public User _AddUser(string account, string password, UserAuthType type)
 {
     throw new NotSupportedException("Not supported for SQL CE!");
 }
Ejemplo n.º 27
0
 public User AddNewUser(string account, string password, UserAuthType type)
 {
     return _DataAdapter._AddUser(account, password, type);
 }
 public User _AddUser(string account, string password, UserAuthType type)
 {
     int userid = Adapters.UserProfilesAdapter.AddUser(account, password, type);
     Reset();
     foreach (User user in _Users)
     {
         if (user.Id == userid.ToString()) return user;
     }
     return null;
 }
Ejemplo n.º 29
0
 public Login(int userId, string name, UserAuthType userAuthType)
 {
     UserId       = userId;
     Name         = name;
     UserAuthType = userAuthType;
 }
Ejemplo n.º 30
0
 private void radioButtonFormUser_Click(object sender, RoutedEventArgs e)
 {
     PasswordRequired();
     _UserAuthType = UserAuthType.FormsAuthentication;
 }
Ejemplo n.º 31
0
 private void radioButtonListUser_Click(object sender, RoutedEventArgs e)
 {
     NoPasswordRequired();
     _UserAuthType = UserAuthType.ListAuthentication;
 }
Ejemplo n.º 32
0
 private void radioButtonActiveDirectoryUser_Click(object sender, RoutedEventArgs e)
 {
     NoPasswordRequired();
     _UserAuthType = UserAuthType.LocalDirectoryAuthentication;
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Adds a user.
 /// </summary>
 /// <param name="account">The account.</param>
 /// <param name="password">The password.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 /// <remarks>
 /// Documented by AAB, 27.02.2009.
 /// </remarks>
 public User _AddUser(string account, string password, UserAuthType type)
 {
     throw new NotSupportedException("Not supported for SQL CE!");
 }
        internal static WsTrustAddress ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
        {
            WsTrustAddress address = null;
            MexPolicy policy = null;
            try
            {
                Dictionary<string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary<string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random random = new Random();
                //try ws-trust 1.3 first
                policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType && p.Version == WsTrustVersion.WsTrust13).OrderBy(p => random.Next()).FirstOrDefault() ??
                         policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();

                if (policy != null)
                {
                    address = new WsTrustAddress();
                    address.Uri = policy.Url;
                    address.Version = policy.Version;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    throw new MsalException(MsalError.IntegratedAuthFailed, new MsalException(MsalError.WsTrustEndpointNotFoundInMetadataDocument));
                }
                else
                {
                    throw new MsalException(MsalError.WsTrustEndpointNotFoundInMetadataDocument);
                }
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return address;
        }
 public static async Task<Uri> FetchWsTrustAddressFromMexAsync(string federationMetadataUrl, UserAuthType userAuthType, CallState callState)
 {
     XDocument mexDocument = await FetchMexAsync(federationMetadataUrl, callState);
     return ExtractWsTrustAddressFromMex(mexDocument, userAuthType, callState);
 }
        private string BuildTokenRequestMessage(UserAuthType authType, string cloudAudienceUri, string username, string password)
        {
            string soapAction;
            string trustNamespace;
            string keyType;
            string requestType;

            if (Version == WsTrustVersion.WsTrust2005)
            {
                soapAction     = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
                trustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                keyType        = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey";
                requestType    = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
            }
            else
            {
                soapAction     = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
                trustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
                keyType        = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
                requestType    = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
            }
            const string wsaNamespaceValue = "http://www.w3.org/2005/08/addressing";

            using (var sw = new StringWriterWithEncoding(Encoding.UTF8))
            {
                using (XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings()
                {
                    Async = false,
                    Encoding = Encoding.UTF8,
                    CloseOutput = false
                }))
                {
                    writer.WriteStartElement("s", "Envelope", EnvelopeNamespaceValue);
                    writer.WriteAttributeString("wsa", "http://www.w3.org/2000/xmlns/", wsaNamespaceValue);
                    writer.WriteAttributeString("wsu", "http://www.w3.org/2000/xmlns/", WsuNamespaceValue);

                    writer.WriteStartElement("Header", EnvelopeNamespaceValue);
                    writer.WriteStartElement("Action", wsaNamespaceValue);
                    writer.WriteAttributeString("mustUnderstand", EnvelopeNamespaceValue, "1");
                    writer.WriteString(soapAction);
                    writer.WriteEndElement(); // Action

                    writer.WriteStartElement("MessageID", wsaNamespaceValue);
#pragma warning disable CA1305                // Specify IFormatProvider - no overload on netcore
                    writer.WriteString($"urn:uuid:{_guidFactory.NewGuid().ToString("D")}");
#pragma warning restore CA1305                // Specify IFormatProvider
                    writer.WriteEndElement(); // messageID

                    writer.WriteStartElement("ReplyTo", wsaNamespaceValue);
                    writer.WriteStartElement("Address", wsaNamespaceValue);
                    writer.WriteString("http://www.w3.org/2005/08/addressing/anonymous");
                    writer.WriteEndElement(); // Address
                    writer.WriteEndElement(); // ReplyTo

                    writer.WriteStartElement("To", wsaNamespaceValue);
                    writer.WriteAttributeString("mustUnderstand", EnvelopeNamespaceValue, "1");
                    writer.WriteString(Uri.ToString());
                    writer.WriteEndElement(); // To

                    if (authType == UserAuthType.UsernamePassword)
                    {
                        AppendSecurityHeader(writer, username, password);
                    }

                    writer.WriteEndElement(); // Header

                    writer.WriteStartElement("Body", EnvelopeNamespaceValue);
                    writer.WriteStartElement("wst", "RequestSecurityToken", trustNamespace);
                    writer.WriteStartElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2004/09/policy");
                    writer.WriteStartElement("EndpointReference", wsaNamespaceValue);
                    writer.WriteStartElement("Address", wsaNamespaceValue);
                    writer.WriteString(cloudAudienceUri);
                    writer.WriteEndElement(); // Address
                    writer.WriteEndElement(); // EndpointReference
                    writer.WriteEndElement(); // AppliesTo

                    writer.WriteStartElement("KeyType", trustNamespace);
                    writer.WriteString(keyType);
                    writer.WriteEndElement(); // KeyType

                    writer.WriteStartElement("RequestType", trustNamespace);
                    writer.WriteString(requestType);
                    writer.WriteEndElement(); // RequestType

                    writer.WriteEndElement(); // RequestSecurityToken

                    writer.WriteEndElement(); // Body
                    writer.WriteEndElement(); // Envelope
                }

                return(sw.ToString());
            }
        }
Ejemplo n.º 37
0
 public User AddNewUser(string account, string password, UserAuthType type)
 {
     return(_DataAdapter._AddUser(account, password, type));
 }
Ejemplo n.º 38
0
        public async Task <HttpResponseMessage> PostFile(string requestUri,
                                                         string filePath, string apiParamName, UserAuthType userAuthType, string userAuthInfo)
        {
            var builder = new HttpRequestBuilder()
                          .AddMethod(HttpMethod.Post)
                          .AddRequestUri(requestUri)
                          .AddContent(new FileContent(filePath, apiParamName));

            SetUserAuthInfo(builder, userAuthType, userAuthInfo);

            return(await builder.SendAsync());
        }
        internal static WsTrustAddress ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
        {
            WsTrustAddress address = null;
            MexPolicy      policy  = null;

            try
            {
                Dictionary <string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary <string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random random = new Random();
                //try ws-trust 1.3 first
                policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType && p.Version == WsTrustVersion.WsTrust13).OrderBy(p => random.Next()).FirstOrDefault() ??
                         policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();

                if (policy != null)
                {
                    address         = new WsTrustAddress();
                    address.Uri     = policy.Url;
                    address.Version = policy.Version;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    throw new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument));
                }
                else
                {
                    throw new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument);
                }
            }
            catch (XmlException ex)
            {
                throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return(address);
        }
        private static void AddPolicy(IDictionary <string, MexPolicy> policies, XElement policy, UserAuthType policyAuthType, bool isWsTrust2005)
        {
            XElement binding = policy.Descendants(XmlNamespace.Sp + "TransportBinding").FirstOrDefault()
                               ?? policy.Descendants(XmlNamespace.Sp2005 + "TransportBinding").FirstOrDefault();

            if (binding != null)
            {
                XAttribute     id      = policy.Attribute(XmlNamespace.Wsu + "Id");
                WsTrustVersion version = WsTrustVersion.WsTrust13;

                if (isWsTrust2005)
                {
                    version = WsTrustVersion.WsTrust2005;
                }

                if (id != null)
                {
                    policies.Add("#" + id.Value, new MexPolicy {
                        Id = id.Value, AuthType = policyAuthType, Version = version
                    });
                }
            }
        }