Exemplo n.º 1
0
 public ExplicitHashCredentials HashCredentials(ICredentials credentials)
 {
     if (credentials is ExplicitHashCredentials hashCred)
     {
         return(hashCred);
     }
     else if (credentials is ExplicitCredentials passCred)
     {
         return(new ExplicitHashCredentials(passCred.Database, passCred.Username, ElementFactory.Local.CalcMd5(passCred.Password)));
     }
     else
     {
         throw new NotSupportedException($"Credentials of type {credentials.GetType().Name} are not supported");
     }
 }
        public static CompliancePolicySyncNotificationClient Create(IConfigurationSession configurationSession, WriteVerboseDelegate writeVerboseDelegate)
        {
            ArgumentValidator.ThrowIfNull("configurationSession", configurationSession);
            OrganizationId organizationId = configurationSession.GetOrgContainer().OrganizationId;

            return(ProvisioningCache.Instance.TryAddAndGetOrganizationDictionaryValue <CompliancePolicySyncNotificationClient, Workload>(CannedProvisioningCacheKeys.OrganizationUnifiedPolicyNotificationClients, organizationId, Workload.SharePoint, delegate()
            {
                if (writeVerboseDelegate != null)
                {
                    writeVerboseDelegate(Strings.VerboseCreateNotificationClient(Workload.SharePoint.ToString()));
                }
                Uri syncSvrUrlFromCache = CompliancePolicySyncNotificationClient.GetSyncSvrUrlFromCache(SyncSvcEndPointType.RestOAuth);
                ICredentials credentials = UnifiedPolicyConfiguration.GetInstance().GetCredentials(configurationSession, null);
                Uri uri = null;
                Uri uri2 = null;
                UnifiedPolicyConfiguration.GetInstance().GetTenantSharePointUrls(configurationSession, out uri, out uri2);
                if (uri == null || uri2 == null || syncSvrUrlFromCache == null)
                {
                    throw new CompliancePolicySyncNotificationClientException(Strings.ErrorCannotInitializeNotificationClientToSharePoint(uri, uri2, syncSvrUrlFromCache));
                }
                SpCompliancePolicySyncNotificationClient result = new SpCompliancePolicySyncNotificationClient(uri, uri2, credentials, syncSvrUrlFromCache);
                if (writeVerboseDelegate != null)
                {
                    writeVerboseDelegate(Strings.VerboseSpNotificationClientInfo(uri, syncSvrUrlFromCache, credentials.GetType().Name));
                }
                return result;
            }));
        }
    public IPromise<string> Login(ICredentials credentials, bool async)
    {
      var result = new Promise<string>();

      _lastCredentials = credentials;
      var database = string.Empty;
      var tokenCred = credentials as TokenCredentials;
      IPromise<IHttpResponse> loginPromise;

      if (tokenCred != null)
      {
        database = tokenCred.Database;
        loginPromise = PolicyToken(PolicyTokenType.connection, null, null, true)
          .Continue(p =>
          {
            return RenewSession(tokenCred.Content, p, true);
          });
      }
      else
      {
        var tokenPromise = (_lastLoginToken == null
                        || _lastLoginToken.Expiration > DateTime.UtcNow.AddSeconds(-5)) ?
        Query(null, null, null, this.SessionPolicy, null, async)
          .Convert<IHttpResponse, InitializeSessionToken>((r, p) =>
          {
            p.Reject(new Exception("Unauthorized error expected"));
          }, (ex, p) =>
          {
            var httpEx = ex as HttpException;
            if (httpEx != null
              && httpEx.Response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
              var header = AuthenticationScheme.Parse(httpEx.Response.Headers["WWW-Authenticate"]);
              var auth = header.FirstOrDefault(a => a.Name == "bearer");
              if (auth == null) throw new InvalidOperationException();
              var ssoAuth = header.FirstOrDefault(a => a.Name == "winsso");

              _lastLoginToken = new InitializeSessionToken(auth.Parameters["token"]
                                      , auth.Parameters["nonce"], auth.Parameters["public_key"]);
              _lastLoginToken.SsoUrl = ssoAuth.Parameters["uri"];
              p.Resolve(_lastLoginToken);
            }
            else
            {
              p.Reject(ex);
            }
          }) :
        Promises.Resolved(_lastLoginToken);

      loginPromise = Promises.All(tokenPromise
                              , PolicyToken(PolicyTokenType.connection, null, null, async))
        .Continue(r =>
        {
          var winCred = credentials as WindowsCredentials;
          if (winCred == null)
          {
            SecureToken password = null;
            var username = string.Empty;

            var explicitCred = credentials as ExplicitCredentials;
            if (explicitCred != null)
            {
              database = explicitCred.Database;
              password = explicitCred.Password;
              username = explicitCred.Username;
            }
            else
            {
              var anon = credentials as AnonymousCredentials;
              if (anon != null)
              {
                database = anon.Database;
              }
              else
              {
                throw new ArgumentException(string.Format("Login credentials must be one of the built-in types, {0} is not supported"
                  , credentials == null, "NULL", credentials.GetType()), "credentials");
              }
            }

            string encodedData;
            var usernameLength = (username == null ? 0 : username.Length);
            var passwordLength = (password == null ? 0 : password.Length);
            var buffer = new byte[3 + 2 * (r.Result1.Nonce.Length + database.Length
                                            + usernameLength + passwordLength)];
            try
            {
              var i = Encoding.UTF8.GetBytes(r.Result1.Nonce, 0, r.Result1.Nonce.Length, buffer, 0);
              buffer[i++] = (byte)'|';
              i += Encoding.UTF8.GetBytes(database, 0, database.Length, buffer, i);
              buffer[i++] = (byte)'|';
              if (usernameLength > 0)
                i += Encoding.UTF8.GetBytes(username, 0, username.Length, buffer, i);
              buffer[i++] = (byte)'|';
              if (passwordLength > 0) password.UseBytes<bool>((ref byte[] b) =>
              {
                for (var j = 0; j < b.Length; j++)
                {
                  buffer[j + i] = b[j];
                }
                i += b.Length;
                return false;
              });

              encodedData = Convert.ToBase64String(r.Result1.Encryptor.Encrypt(buffer, 0, i));
            }
            finally
            {
              for (var j = 0; j < buffer.Length; j++)
              {
                buffer[j] = 0;
              }
            }
            return Query(r.Result1.Content + " " + encodedData, "ValidateUser", "<Item/>"
              , this.SessionPolicy , r.Result2, async);
          }
          else
          {
            // Windows authentication
            return Query(r.Result1.SsoUrl, r.Result1.Content, "ValidateUser", "<Item/>"
              , this.SessionPolicy, r.Result2, winCred.Credentials, async
              , req => req.SetHeader("DATABASE", winCred.Database));
          }
        });
      }

      loginPromise.Progress((p, m) => result.Notify(p, m))
        .Done(r => {
          _database = database;

          var data = r.AsXml().DescendantsAndSelf("Result").FirstOrDefault();
          _userId = data.Element("id").Value;

          var auth = data.Element("Authorization");
          _renewalToken = new TokenCredentials(auth.Element("refresh_token").Value);
          _renewalToken.Database = database;
          SetSessionToken(auth.Element("access_token").Value
            , int.Parse(auth.Element("expires_in").Value));

          var i18n = data.Element("i18nsessioncontext");
          var context = new ServerContext();
          context.DefaultLanguageCode = i18n.Element("default_language_code").Value;
          context.DefaultLanguageSuffix = i18n.Element("default_language_suffix").Value;
          context.LanguageCode = i18n.Element("language_code").Value;
          context.LanguageSuffix = i18n.Element("language_suffix").Value;
          context.Locale = i18n.Element("locale").Value;
          context.TimeZone = i18n.Element("time_zone").Value;
          _factory = new ElementFactory(context);

          var upload = data.Element("WriteVault") == null
            ? null : data.Element("WriteVault").Element("Item");
          if (upload == null)
          {
            var strategy = new DefaultVaultStrategy();
            strategy.Initialize(this);
            _writeVault = strategy.WritePriority(true).Convert(v => v.First());
          }
          else
          {
            _writeVault = Promises.Resolved(Vault.GetVault(
              (IReadOnlyItem)_factory.FromXml(upload.ToString())));
          }

          result.Resolve(_userId);
        }).Fail(ex => {
          var httpEx = ex as HttpException;
          if (httpEx != null
            && httpEx.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
          {
            var auth = AuthenticationScheme.Parse(httpEx.Response.Headers["WWW-Authenticate"])
              .FirstOrDefault(a => a.Name == "bearer");
            string msg;
            if (auth != null && auth.Parameters.TryGetValue("error_description", out msg))
            {
              result.Reject(new Exception("Error logging in: " + msg));
            }
            else
            {
              result.Reject(new Exception("Unanticipated error logging in."));
            }
          }
          else
          {
            result.Reject(ex);
          }
        });
      result.CancelTarget(loginPromise);

      return result;
    }
        /// <summary>
        /// Build an HttpClientHandler instance with proxy settings, if necessary. Proxy used is System.Net.WebRequest.DefaultWebProxy
        /// </summary>
        /// <param name="proxyUri"></param>
        /// <param name="credentials">The credentials to use for an authenticated proxy. null if none.</param>
        /// <param name="enableDefaultSystemAuthentication">if True ==> call HttpClientHandler.UseDefaultCredentials = true</param>
        /// <returns>The HtpClientHandler.</returns>
        internal static HttpClientHandler Build(string proxyUri, ICredentials credentials, bool enableDefaultSystemAuthentication)
        {
            Debug("httpClientHandler.UseDefaultCredentials: " + enableDefaultSystemAuthentication);

            Proxy proxy = null;
            // Used to test if have Proxy defined in IE
            String proxyUriToUse = null;

            // Test if used the default Web Proxy or the one passed in connection string:
            if (proxyUri == null)
            {
                proxyUriToUse = System.Net.WebRequest.DefaultWebProxy.GetProxy(new Uri("http://www.google.com")).ToString();
            }
            else
            {
                proxy         = new Proxy(proxyUri);
                proxyUriToUse = proxy.GetProxy(new Uri("http://www.google.com")).ToString();
            }

            Debug("uriProxy: " + proxyUriToUse);

            if (credentials != null && credentials.GetType() == typeof(NetworkCredential))
            {
                Debug("credentials: " + ((NetworkCredential)credentials).UserName + "/" + ((NetworkCredential)credentials).Password);
            }

            if (proxyUriToUse.Contains("http://www.google.com"))
            {
                Debug("System.Net.WebRequest.DefaultWebProxy is default");
                HttpClientHandler httpClientHandler = new HttpClientHandler();
                if (enableDefaultSystemAuthentication)
                {
                    httpClientHandler.UseDefaultCredentials = true;
                }
                return(httpClientHandler);
            }
            else
            {
                HttpClientHandler httpClientHandler = new HttpClientHandler
                {
                    UseProxy = true,
                    UseDefaultCredentials = false
                };

                if (proxy == null)
                {
                    httpClientHandler.Proxy = System.Net.WebRequest.DefaultWebProxy;
                }
                else
                {
                    httpClientHandler.Proxy = proxy;
                }

                httpClientHandler.Proxy.Credentials = credentials;
                httpClientHandler.PreAuthenticate   = true;
                if (enableDefaultSystemAuthentication)
                {
                    httpClientHandler.UseDefaultCredentials = true;
                }
                return(httpClientHandler);
            }
        }