Как обновить семейство сайтов онлайн-ресурса с помощью приложения funtion - PullRequest
0 голосов
/ 09 марта 2020

Я использую функцию azure для разработки некоторых функций по созданию семейств сайтов. Мои шаги, как показано ниже:

  1. с использованием admin для создания семейств сайтов (по клиентским и клиентским секретам)
  2. получить новый клиентский контекст URl для обновления некоторых сведений, таких как владельцы сайтов членов группы и т. Д. c

Теперь я сталкиваюсь с проблемой, что сначала я использую учетную запись и пароль для получения новый контекст клиента, а затем обновить свойство сайта, но теперь не может использовать его, чтобы вызвать новую политику корпорации. Как я могу улучшить этот метод, чтобы решить эту проблему?

public ClientContext GetClientContextByCredential(SharePointOnlineCredentials cred, bool tryNewSite)
        {
            ClientContext ctx = ContextInit;
            try
            {
                ctx.Credentials = cred;
                Web web = ctx.Web;
                ctx.Load(web, w => w.Url);
                ctx.ExecuteQuery();

                return ctx;
            }
            catch (Exception ex)
            {
                ctx = null;
                if (_logHelper != null)
                {
                    if (tryNewSite)
                    {
                        _logHelper.writeLog(ex.Message, TraceLevel.Info, ex);
                    }
                    else
                        _logHelper.writeLog(ex.Message, TraceLevel.Error, ex);
                }
                return ctx;
            }
        }

такая ошибка будет происходить при использовании SharePointOnlineCredentials

The remote server returned an error: (401) Unauthorized.

1 Ответ

1 голос
/ 11 марта 2020

Если вы хотите использовать приложение Azure AD для подключения к SharePoint через Интернет, выполните следующие действия

  1. Создание приложения Azure AD
Connect-AzureAD 

# Create the self signed cert if you have the cert, please skip it
$currentDate = Get-Date
$endDate  = $currentDate.AddYears(1)
$notAfter  = $endDate.AddYears(1)
$pwd  = "<password>"
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName com.foo.bar -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath c:\temp\examplecert.pfx -Password $pwd

# Load the certificate
$cert  = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\temp\examplecert.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())


# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://test123"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue

Настройка разрешений через Azure Портал enter image description here

Загрузка сертификата в Azure хранилище ключей

$Password = ConvertTo-SecureString -String "123" -AsPlainText -Force
Import-AzKeyVaultCertificate -VaultName "ContosoKV01" -Name "ImportCert01" -FilePath "C:\temp\examplecert.pfx" -Password $Password

Настройка Azure функция

a. Настройка MSI для приложения функции enter image description here enter image description here

b. Создайте политику доступа в хранилище ключей для идентификатора приложения, который вы создали ранее. Включите секретное разрешение «Получить» для этой политики.

c. код

public ClientContext GetClientContextByCredential()
      {
          ClientContext ctx = ContextInit;
          try
          {
               ctx  = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(
      siteUrl,
      ApplicationId,
      tenant + ".onmicrosoft.com",
      GetKeyVaultCertificate("kv-spo", "AzureAutomationSPOAccess")))
      {
      ctx  .Load(cc.Web, p => p.Title);
      ctx  .ExecuteQuery();

              return ctx;
          }
          catch (Exception ex)
          {
              ctx = null;
              if (_logHelper != null)
              {
                  if (tryNewSite)
                  {
                      _logHelper.writeLog(ex.Message, TraceLevel.Info, ex);
                  }
                  else
                      _logHelper.writeLog(ex.Message, TraceLevel.Error, ex);
              }
              return ctx;
          }
      }

 internal static X509Certificate2 GetKeyVaultCertificate(string keyvaultName, string name)
{


      var serviceTokenProvider = new AzureServiceTokenProvider();
     var  keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(serviceTokenProvider.KeyVaultTokenCallback));


  // Getting the certificate
  var secret = keyVaultClient.GetSecretAsync("https://" + keyvaultName + ".vault.azure.net/", name);

  // Returning the certificate
  return new X509Certificate2(Convert.FromBase64String(secret.Result.Value));


}

Подробнее см.

https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azuread

https://docs.microsoft.com/en-us/archive/blogs/richard_dizeregas_blog/performing-app-only-operations-on-sharepoint-online-through-azure-ad

...