Настройка проверки подлинности на основе утверждений с помощью Windows Live ID (SharePoint Server 2010)

 

Применимо к: SharePoint Foundation 2010, SharePoint Server 2010

Последнее изменение раздела: 2016-11-30

Проверка подлинности на основе утверждений в Microsoft SharePoint Server 2010 позволяет делегировать проверку подлинности службе маркеров безопасности Windows Live ID. Это важно в том случае, если для управления паролями планируется использовать Windows Live ID. Служба Windows Live ID настроена в качестве поставщика удостоверений для SharePoint Server 2010. Между SharePoint Server 2010 и службой Windows Live ID устанавливается одностороннее отношение доверия, основанное на сертификате. Когда пользователь предоставляет учетные данные Windows Live ID, служба Windows Live ID возвращает идентификатор PUID (Passport Unique Identity) и сообщение электронной почты, инкапсулированные в маркер утверждений SAML версии 1.1. Этот маркер утверждений шифруется с помощью открытого ключа Windows Live ID, который входит в XML-код метаданных Windows Live ID.

Дополнительные сведения о службе Windows Live ID см. в указанных ниже ресурсах.

Куки-файл Windows Live ID кэшируется на клиентском компьютере и отправляется SharePoint Server 2010 в виде ответа POST на успешный запрос проверки подлинности. SharePoint Server 2010 преобразует маркер SAML Windows Live ID в маркер SAML SharePoint Server 2010. Идентификатор PUID для пользователя создается на основе утверждения имени участника-пользователя (UPN), возвращенного в маркере SAML. Это значение используется в SharePoint Server 2010 для идентификации пользователя и управления доступом. SharePoint Server 2010 может объединять маркеры пользователей с дополнительными утверждениями с помощью пользовательского поставщика утверждений, настроенного в веб-приложении SharePoint Server 2010. Куки-файл SharePoint Server 2010 также возвращается на клиентский компьютер и кэшируется для последующих запросов. По истечении срока действия куки-файла Windows Live ID или SharePoint Server 2010 пользователь перенаправляется на сервер Windows Live ID.

Содержание:

  • Настройка службы маркеров безопасности Windows Live ID

  • Настройка SharePoint для проверки подлинности Windows Live ID

  • Преобразование внутренней среды Windows Live ID в производственную среду

  • Создание различных типов веб-приложений SharePoint на основе утверждений

  • Предоставление разрешений всем пользователям Windows Live ID, прошедшим проверку подлинности

Настройка службы маркеров безопасности Windows Live ID

Протокол WS-Federation реализован в службе Windows Live ID и предоставляет инфраструктуру службы маркеров безопасности Live ID, назначенной в качестве доверенного поставщика удостоверений. Можно извлечь открытый сертификат Windows Live ID из узла X509Certificate XML-кода метаданных и сохранить его в виде сертификата безопасности Интернета (CER-файла). Если XML-код метаданных содержит несколько узлов X509Certificate, можно выбрать любой из них. Предоставьте в этом сертификате (CER-файле) доступ на чтение учетной записи пула приложений фермы SharePoint Server 2010.

Настройте Microsoft Services Manager (MSM) с помощью указанных ниже значений.

Значение Описание

Имя домена

Имя домена, для которой будут создаваться запросы проверки подлинности к службе маркеров безопасности Live ID. Укажите полное доменное имя (FQDN).

URL-адрес возврата по умолчанию

URL-адрес, на который служба маркеров безопасности Windows Live ID будет перенаправлять пользователя после успешной проверки подлинности, например: https://username.global.corp.contoso.com/_trust/default.aspx.

DNS-имя

Уникальный идентификатор, предоставляемый в запросе проверки подлинности к службе маркеров-безопасности Windows Live ID. Этот идентификатор позволяет выполнять поиск URL-адреса возврата по умолчанию. DNS-имя должно соответствовать значению области, указанному в запросе проверки подлинности Windows Live ID.

Параметр WRealm

Параметр WRealm должен соответствовать полю DNS в конфигурации сайта MSM. Параметр WRealm необходимо создать в одном из следующих форматах: нижний_уровень.домен.верхний_уровень или Urn:домен:имя.

Переопределение политики проверки подлинности

Переопределение политики проверки подлинности настраивается с помощью следующего значения: MBI_FED_SSL.

Настройка SharePoint для проверки подлинности Windows Live ID

В данном разделе приведены процедуры для настройки SharePoint Server 2010 для проверки подлинности Windows Live ID.

Настройка SharePoint для проверки подлинности Windows Live ID с помощью Windows PowerShell

  1. Проверьте, выполняются ли следующие минимальные требования: См. статью Add-SPShellAdmin.

  2. В меню Пуск выберите пункт Все программы.

  3. Выберите пункт Продукты Microsoft SharePoint 2010.

  4. Щелкните компонент Командная консоль SharePoint 2010.

  5. В командной строке Windows PowerShell (PS C:\>) задайте значение области, соответствующее DNS-имени, указанному в Microsoft Services Manager. Значение области в Windows Live ID должно соответствовать правильному DNS-имени, как показано в приведенном ниже примере.

    $realm = "urn:" + $env:ComputerName + ":ServerName"
    
  6. Получите значение идентификатора PUID учетной записи, которая будет использоваться в качестве учетной записи администратора фермы; для этого сначала зарегистрируйтесь на следующем веб-сайте: Windows Live ID(https://accountservices.passport.net), а затем перейдите к полю Unique ID на странице "Учетные записи".

  7. Укажите значение идентификатора PUID в следующем формате: PUID@live.com.

  8. Найдите в следующем источнике один из узлов <X509Certificate>: URL-адрес XML-кода метаданных (https://nexus.passport-int.com/federationmetadata2/2007-06/federationmetadata.xml).

  9. Скопируйте в буфер обмена содержимое любого из двух узлов X509Certificate, как показано в приведенном ниже примере.

    MIICWzCCAcSgAwIBAgIJAJEzHoaEodSoMA0GCSqGSIb3DQEBBQUAMCkxJzAlBgNV
    BAMTHkxpdmUgSUQgU1RTIFNpZ25pbmcgUHVibGljIEtleTAeFw0wODEwMzAyMjA5
    MjNaFw0xMzEwMjkyMjA5MjNaMCkxJzAlBgNVBAMTHkxpdmUgSUQgU1RTIFNpZ25p
    bmcgUHVibGljIEtleTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArz97XPae
    GNAC4UnKl5zReyhgk3Bzf08U+CgD0R9+GZOahmpakJXFpI213gQWiHrUGaMN9nsK
    4kzSfDPiquAMsV6vBYyWuPLZ0XrMzTAOV/WHSK3bCsYWWQZeH9Xn8G1Hkz+gQSC/
    92lBbq9oBCZfLv3OlkobOmT8d+ldRKGU4pUCAwEAAaOBijCBhzAdBgNVHQ4EFgQU
    VbJyIcGL0AjB4/Wm4DqUZux6uUkwWQYDVR0jBFIwUIAUVbJyIcGL0AjB4/Wm4DqU
    Zux6uUmhLaQrMCkxJzAlBgNVBAMTHkxpdmUgSUQgU1RTIFNpZ25pbmcgUHVibGlj
    IEtleYIJAJEzHoaEodSoMAsGA1UdDwQEAwIBxjANBgkqhkiG9w0BAQUFAAOBgQAO
    /5vGfu+Vg1TKBuxsAIMqjqKXX7aRrANNZM/5ACdwAUtMDG/n8INoXgOKr851fbF6
    4yBesmFjg2TbR8y0/ITAD+d+iyEpR7IO3/is9rWAj4ggbw8yqaDWn26eh3bAdoa+
    p38qtqJHkUGF5vApeHiu6zO573bKs+nXcKVM8mNbjA==
    
  10. Вставьте из буфера обмена содержимое любого из узлов X509Certificate в блокнот и сохраните файл под следующим именем: LiveID-INT.cer.

  11. Настройте сертификат Windows Live ID (извлеченный из XML-файла метаданных), как показано в приведенном ниже примере.

    $certloc = "C:\LiveIDWithSAML\LiveID-INT.cer"
    
  12. Задайте в SharePoint Server 2010 новый доверенный корневой центр сертификации, как показано в приведенном ниже примере.

    $rootcert = Get-PfxCertificate $certloc
    New-SPTrustedRootAuthority "NewRootAuthority" -Certificate $rootcert | Out-Null
    
  13. Создайте объект с сертификатом Windows Live ID, как показано в приведенном ниже примере.

    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certloc)
    
  14. Определите утверждение, которое будет использоваться в качестве уникального идентификатора пользователя. Сопоставьте утверждение имени участника-пользователя (UPN) зарезервированному идентификатору имени утверждения. При этом также будет сопоставлено утверждение адреса электронной почты, как показано в приведенном ниже примере.

    $map1 = New-SPClaimTypeMapping -IncomingClaimType "https://schemas.xmlsoap.org/claims/EmailAddress" -IncomingClaimTypeDisplayName "https://schemas.xmlsoap.org/claims/EmailAddress" -SameAsIncoming
    $map2 = New-SPClaimTypeMapping -IncomingClaimType "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" -IncomingClaimTypeDisplayName "UPN" -LocalClaimType "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
    
  15. Для нового веб-приложения создайте нового поставщика проверки подлинности SharePoint Server 2010, как показано в следующем примере.

    $apSAML = New-SPTrustedIdentityTokenIssuer -Name "LiveID" -Description "LiveID" -Realm $realm -ImportTrustCertificate $cert -ClaimsMappings $map1,$map2 -SignInUrl "https://login.live-int.com/login.srf" -IdentifierClaim "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
    
  16. Чтобы использовать поставщика проверки подлинности, созданного на предыдущем шаге, создайте новое веб-приложение SharePoint Server 2010, как показано в следующем примере.

    $waurl = https://" + $env:ComputerName - You might use FQDN url of your site here.
    $title = "Site Title"
    $waexe = New-SPWebApplication -Name $title -ApplicationPool $title -ApplicationPoolAccount $owner -Url $waurl -AuthenticationProvider
    $scexe = New-SPSite $siteurl -Name $title -Description $title -Template 'STS#1' -OwnerAlias
    
  17. Запустите IIS, введя в командной строке INETMGR.

  18. Зайдите на сайт Веб-приложение на основе утверждений в IIS.

  19. В левой области щелкните правой кнопкой мыши Веб-приложение на основе утверждений и выберите команду Изменить привязки.

  20. Выберите https и щелкните Правка.

  21. В разделе Сертификат SSL выберите один из перечисленных сертификатов. Рассмотрите возможность использования самозаверяющего сертификата.

  22. Импортируйте общедоступный сертификат Windows Live ID в папки Локальный компьютер, SharePoint Server 2010 и Доверенные лица.

Преобразование внутренней среды Windows Live ID в производственную среду

Чтобы преобразовать идентификатор Windows Live ID для внутренней среды в идентификатор для производственной среды, используйте инструкции, приведенные в этом разделе.

Преобразование идентификатора Windows Live ID для внутренней среды в идентификатор для производственной среды

  1. Убедитесь, что сайт перенесен в производственную среду в MSM и все требования к системе соблюдены. Если среда Windows Live ID в MSM является внутренней, то проверка соблюдения требований к системе не требуется.

  2. Убедитесь, что для политики проверки подлинности производственной среды Windows Live ID задано значение MBI_FED_SSL.

  3. Поскольку политика проверки подлинности производственной среды настроена для использования транспорта SSL, убедитесь, что производственная среда Windows Live ID использует URL-адреса на основе протокола HTTPS. Сайты производственной среды отправляют запросы POST по протоколу SSL веб-сайту https://login.live.com/. В объекте SPTrustedIdentityTokenIssuer содержится URI поставщика, который должен быть URI учетной записи Live. Убедитесь, что URI учетной записи Live использует протокол HTTPS.

  4. Если поставщик утверждений Windows Live ID вместо PUID использует адрес электронной почты, сайт производственной среды должен находиться в группе политик Майкрософт. Помните, что для внутренних партнеров утверждение этой группы политик осуществляется автоматически, а для внешних партнеров требуется явное утверждение.

Создание различных типов веб-приложений SharePoint на основе утверждений

Чтобы запустить скрипт Windows PowerShell, создающий различные типы веб-приложений на основе утверждений SharePoint Server 2010, используйте инструкции, приведенные в этом разделе.

Создание различных типов веб-приложений SharePoint на основе утверждений с помощью Windows PowerShell

  1. Проверьте, выполняются ли следующие минимальные требования: См. статью Add-SPShellAdmin.

  2. В меню Пуск выберите пункт Все программы.

  3. Выберите пункт Продукты Microsoft SharePoint 2010.

  4. Щелкните компонент Командная консоль SharePoint 2010.

  5. В командной строке Windows PowerShell запустите скрипт DeployLiveIdWithSAML, как показано в следующем примере.

    #.SYNOPSIS
    #    Script for creating different types of claims web applications from the Windows PowerShell command line.
    #.DESCRIPTION
    #    Script will create ANON, WIN, FBA, MULTI, MIXED, SAML and combinations of these web applications.
    #.NOTES
    #    Script: ClaimsWA.ps1
    #    Remark: The script will load/unload additional snap-ins depending on where it's being executed from.
    #    Update: 1/15/2010 (v2.0)
    #.PARAMETER type
    #   Indicates the type of claims web app to create (see examples for full list of valid supported types)
    #If not specified, this will default to ALL and each of the supported types of claims web apps will be created
    #.PARAMETER port
    #   Indicates the port number to create the web app on (See reserved ports at https://support.microsoft.com/kb/832017/ru-ru)
    #If not specified, this will default to port 201 and will be incremented in sequence for multiple web apps
    #.PARAMETER owner
    #   Indicates the domain account that will be used for App Pool (should be registered as a SharePoint Server managed account)
    #If not specified, this will default to logged on user and will use USERDOMAIN & USERNAME environment values
    #.EXAMPLE
    #   claimswa.ps1 WIN (create WIN-claims web app at port# 201 and use logged on user for app pool account)
    #   Here are some more examples of HOWTO use the script:
    #      claimswa.ps1 ANON (create ANON web app at port# 201)
    #      claimswa.ps1 ANON/FBA 701 (create ANON/FBA web app at port# 701)
    #      claimswa.ps1 FBA (create FBA web app at port# 201 using LDAP provider; default is REDMOND instance)
    #      claimswa.ps1 FBA/IBM (create FBA web app at port# 201 using LDAP provider pointing to the IBM instance)
    #      claimswa.ps1 FBA/SQL 851 (create forms-based authentication web app at port# 851 using SQL provider)
    #      claimswa.ps1 WIN/FBA/MIXED 501 (create Windows/forms-based authentication mixed-mode web apps at port# 501)
    #      claimswa.ps1 WIN/SAML/MULTI 901 (create Windows/SAML multi-auth web apps at port# 901)
    #   Here is the full list of all the support TYPEs (combine options delimited with slash for your config):
    #   Basic auth types:
    #      WIN   : create Windows claims web application on the port# specified on command line
    #      FBA   : create forms-based authentication claims web apps with the specified membership provider (SQL Server/LDAP listed below)
    #      SAML  : create SAML-claims web application on the default HTTPS port# 443
    #      ANON  : indicator switch for creating the web application to allow ANON mode
    #   Complex auth types:
    #      MULTI : create claims web application with multiple auth types using a single URL to access
    #      MIXED : create claims web application with multiple auth types using multiple URLs to access
    #   FBA membership/rolemanager providers
    #      RED   : use the REDMOND domain LDAP provider; this is the default setting if a provider is not specified
    #      SQL   : use the SQL Server provider for connecting to forms-based authentication web apps (connects to the ASPNETDB instance on ZADANG)
    #      PPL   : use the PEOPLEDC domain LDAP provider that is a private domain used for testing PEOPLE features
    #      SUN   : use the SUNOne LDAP provider in the PEOPLEDC domain which is used for profile import/sync testing
    #      IBM   : use the IBM LDAP provider in the PEOPLEDC domain which is used for profile import/sync testing
    #      NVL   : use the Novell LDAP provider in the PEOPLEDC domain which is used for profile import/sync testing
    
    # TODO (no specific ETA for these updates):
    #    1. Set the default IIS cert bindings for SAML web
    #    2. Use IIS CMDlets instead of updating XML object
    #    3. We should be able to define MixedMode base auth
    #    4. Use the domain for logged on user for LDAP string
    #    5. Do not attempt to write to CA/STS if running on WFE
    
    
    # Define the args list that we will accept & work with
    param ([string]$type, [int]$port, [string]$owner)
    
    function main() {
        # Valid options list
        $auths  = @("WIN", "FBA", "SAML", "ANON")
        $extnd  = @("MULTI", "MIXED")
        $provs  = @("SQL", "RED", "PPL", "SUN", "IBM", "NVL")
        $optns  = @("APP", "FIX")
        $typeOK = $true
    
        # Do we have the minimum args data before we can proceed
        # I'm not doing extensive validation but at least minimum
        foreach ($arg in $type.split("/")) {
            if (($auths+$extnd+$optns+$provs) -notcontains $arg) {
                write-host -Fore Red "`nInvalid TYPE argument was specified; execution aborted!`nTo see a list of valid TYPEs, execute with -examples option`n"
                $typeOK=$false; break
            }
        }
    
        if ($typeOK) {
            $type = @($type.toupper().split("/") | Sort | Get-Unique)
            switch ($type.count) {
                1 {
                    foreach ($arg in $type) {
                        if (($auths+$extnd+$optns) -notcontains $arg) {
                            write-host -Fore Red "`nInvalid AUTH argument was specified; execution aborted!`nTo see a list of valid AUTHs, execute with -examples option`n"
                            $typeOK=$false; break
                        }
                    }
                    if (($type -eq "MULTI") -or ($type -eq "MIXED")) {
                        $type += @("WIN", "FBA"); write-host -Fore Yellow "MULTI/MIXED auth combo not specified; defaulting to $type"
                    }
                    if ($type -eq "ANON") {
                        $type += @("WIN"); write-host -Fore Yellow "ANON auth combo not specified; defaulting to $type"
                    }
                }
    
                2 {
                    if ($type -contains "ANON") {
                        foreach ($arg in $type) {
                            if ($auths -notcontains $arg) {
                                write-host -Fore Red "`nInvalid ANON combo was specified; execution aborted!`nTo see a list of valid PROVIDERs, execute with -examples option`n"
                                $typeOK=$false; break
                            }
                        }
                    }
                    else {
                        $multiOK=$true
                        foreach ($arg in $type) {
                            if ($auth -notcontains $arg) {
                                $multiOK=$false; break
                            }
                        }
                        if ($multiOK) {$type += @("MULTI"); write-host -Fore Yellow "Multiple auth types specified; defaulting to $type"}
                    }
                }
            }
    
            if (($type -contains "MULTI") -or ($type -contains "MIXED") -and ($type.count -lt 3)) {
                write-host -Fore Red "`nMULTI/MIXED option requires 2 base auth types be specified!`nTo see a list of valid TYPEs, execute with -examples option`n"
                $typeOK=$false
            }
        }
    
        if ($typeOK) {
            # We seem to have the TYPE argument, let's check the others
    
            if (-not $port) {
                if ($type -contains "SAML") {$port=443} else {$port=201}
                write-host -Fore Yellow "PORT not specified; defaulting to $port"
            }
    
            if (-not $owner) {
                $owner = $env:UserDomain + "\" + $env:UserName.tolower()
                write-host -Fore Yellow "OWNER not specified; defaulting to $owner"
            }
    
            #In case somebody attempts to execute this script in the regular PS/ISE console,
            #let's load the IIS/SP snap-in to ensure we have everything we need to work with
            Manage-SnapIns (1)
    
            # check what flavor of SERVER we're running
            $product = Get-SPProduct | Where-Object {$_.ProductName.contains("SharePoint Server 2010")};
            if ($product.ProductName.contains("Debug")) {$flavor="DEBUG"} else {$flavor="SHIP"}
            write-host -Fore Green "Detected $flavor flavor of MOSS installed on this farm!"
    
            if ($type -contains "APP") {
                Write-WEBConfigs 0 "APP"
            }
            elseif ($type -contains "FIX") {
                Fix-Environment
            }
            else {
                Create-WebApp $type $port
            }
    
            # We're done with the snap-ins, so let's unload them
            Manage-SnapIns (0)
        }
    }
    
    function Fix-Environment {
        # This is just a series of steps to clean up
        # Not recommended to use unless you know why!
        Remove-SPTrustedRootAuthority NewRootAuthority
        Remove-SPTrustedIdentityTokenIssuer ServerName
    
        # I need to add the other clean up stuff here...
    }
    
    # This is the core script block that creates the different web apps
    function Create-WebApp ([string]$type, [int]$port) {
        $waurl = http://" + $env:ComputerName
    
        if ($type.contains("SAML")) { $waurl = $waurl.replace("http", "https") }
        $siteurl = $waurl + ":" + $port
        $title = "ClaimsWA-$port-" + $type.replace(" ","-")
    
        # Let's construct the WA/SC CMDlet call that we'll invoke later
        $waexe = "New-SPWebApplication -Name $title -ApplicationPool $title -ApplicationPoolAccount $owner -Url $waurl -AuthenticationProvider"
        $scexe = "New-SPSite $siteurl -Name $title -Description $title -Template 'STS#1' -OwnerAlias"
    
        write-host -Fore Cyan "`nSetting up $title on port $port now:"
    
        if ($type.contains("WIN")) {
            $apWIN = New-SPAuthenticationProvider -DisableKerberos:$true
            $cpWIN = New-SPClaimsPrincipal -Identity $owner -IdentityType 1
        }
    
        if ($type.contains("FBA")) {
            if ($type.contains("SQL")) {
                $membership="SQLms"; $rolemanager="SQLrm"; $identity = "sqlms:user1"
            }
            elseif ($type.contains("PPL")) {
                $membership="PPLms"; $rolemanager="PPLrm"; $identity = "pplms:fbauser1"
            }
            elseif ($type.contains("SUN")) {
                $membership="SUNms"; $rolemanager="SUNrm"; $identity = "sunms:fbauser1"
            }
            elseif ($type.contains("IBM")) {
                $membership="IBMms"; $rolemanager="IBMrm"; $identity = "ibmms:fbauser1"
            }
            elseif ($type.contains("NVL")) {
                $membership="NVLms"; $rolemanager="NVLrm"; $identity = "nvlms:fbauser1"
            }
            else {
                $membership="REDms"; $rolemanager="REDrm"; $identity = ("redms:$env:UserName").tolower()
            }
    
            $apFBA = New-SPAuthenticationProvider -ASPNETMembershipProvider $membership -ASPNETRoleProviderName $rolemanager;
            $cpFBA = New-SPClaimsPrincipal -Identity $identity -IdentityType 4
        }
    
        if ($type.contains("SAML")) {                
            $realm = "urn:" + $env:ComputerName + ":ServerName"
            $user  = "000300008448E34D@live.com" 
            $certloc = "C:\LiveIDWithSAML\LiveID-INT.cer"
    
            $rootcert = Get-PfxCertificate $certloc
            New-SPTrustedRootAuthority "NewRootAuthority" -Certificate $rootcert | Out-Null
    
           $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certloc)
           $map1 = New-SPClaimTypeMapping -IncomingClaimType "https://schemas.xmlsoap.org/claims/EmailAddress" -IncomingClaimTypeDisplayName "https://schemas.xmlsoap.org/claims/EmailAddress" -SameAsIncoming
           $map2 = New-SPClaimTypeMapping -IncomingClaimType "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" -IncomingClaimTypeDisplayName "UPN" -LocalClaimType "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
    
           $apSAML = New-SPTrustedIdentityTokenIssuer -Name "LiveID" -Description "LiveID" -Realm $realm -ImportTrustCertificate $cert -ClaimsMappings $map1,$map2 -SignInUrl "https://login.live-int.com/login.srf" -IdentifierClaim "https://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
           $cpSAML = New-SPClaimsPrincipal -TrustedIdentityTokenIssuer $apSAML -Identity $user.tolower()
        }
    
        if ($type.contains("WIN")) {
            $waexe += " `$apWIN"; $scexe += " `$cpWIN.ToEncodedString()"
        }
        elseif ($type.contains("FBA")) {
            $waexe += " `$apFBA"; $scexe += " `$cpFBA.ToEncodedString()"
        }
        else {
            $waexe += " `$apSAML -SecureSocketsLayer"; $scexe += " `$cpSAML.ToEncodedString()"
        }
    
        if ($type.contains("MULTI")) {
            if ($type.contains("WIN")) {
                if ($type.contains("FBA")) {
                    $waexe += ",`$apFBA"; $scexe += " -SecondaryOwnerAlias `$cpFBA.ToEncodedString()"
                }
                if ($type.contains("SAML")) {
                    $waexe += ",`$apSAML -SecureSocketsLayer"; if (!$scexe.contains("Secondary")) { $scexe += " -SecondaryOwnerAlias `$cpSAML.ToEncodedString()" }
                }
            }
            else {
                $waexe += ",`$apSAML -SecureSocketsLayer"; $scexe += " -SecondaryOwnerAlias `$cpSAML.ToEncodedString()"
            }
        }
    
        # Check if we're creating the ANON web apps
        if ($type.contains("ANON")) { $waexe += " -AllowAnonymousAccess" }
    
        $waexe += " -Port $port | Out-Null"; $scexe += " | Out-Null"
    
        write-host -Fore Cyan "Deploying app..." -noNewLine
        Invoke-Expression $waexe
    
        # We could do this with a simple if/else but there may be other auth types too
        if ($type.contains("WIN"))  { Create-UserPolicy $siteurl $cpWIN.ToEncodedString()  }
        if ($type.contains("FBA"))  { Create-UserPolicy $siteurl $cpFBA.ToEncodedString()  }
        if ($type.contains("SAML")) { Create-UserPolicy $siteurl $cpSAML.ToEncodedString() }
    
        write-host -Fore Cyan "Creating site..." -noNewLine
        Invoke-Expression $scexe
    
        # If this is the ANON web app, then set the root site access to entire web
        if ($type.contains("ANON")) { $web = Get-SPWeb $siteurl; $web.AnonymousState="On"; $web.Update() }
    
        # At this time, let's also check if it's going to be a MixedMode web app
        if ($type.contains("MIXED")) {
            # If it's a Mixed-Mode web app we need to extend the base app to another auth type too
            $port++; write-host -Fore Cyan "Extending port $port..." -noNewLine
            $waurl = $waurl.replace("https", "http")
            $waexe = "Get-SPWebApplication $siteurl | New-SPWebApplicationExtension -Name $title-Ext -Zone `"Intranet`" -URL $waurl -Port $port -AuthenticationProvider"
            if ($type.contains("WIN")) {
                if ($type.contains("FBA")) { $waexe += " `$apFBA" } else { $waexe += " `$apSAML" }
            }
            else {
                $waexe += " `$apSAML"
            }
            Invoke-Expression $waexe
        }
    
        # If we've created a FBA web app, then it's time to update the CA/STS/FBA web.config files
        if ($type.contains("FBA")) { Write-WEBConfigs 0 $port.tostring() }; write-host -Fore Cyan "done!"
    }
    
    function Create-UserPolicy ([string]$weburl, [string]$encodeduser) {
        $webapp = Get-SPWebApplication $weburl
        $policy = $webapp.Policies.Add($encodeduser, "ClaimsWA.ps1 User")
        $role = $webapp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)
        $policy.PolicyRoleBindings.Add($role)
        $webapp.Update()
    }
    
    function Write-WEBConfigs ([int]$begin, [string]$vroot) {
        # For now I'm using the XML object to load/save the config files
        # Eventually we should use the IIS:CMDlets from WebAdministration
    
        write-host -Fore Cyan "Writing WEBConfig..." -noNewLine
        #$filei = "\\back\scratch\suntoshs\backup\webconfigs.xml"
        $filei = "\\back\scratch\suntoshs\scripts\oobinstall\webconfigs.xml"
    
        $xmli = [xml](get-content $filei)
        $root = $xmli.get_DocumentElement()
    
        for ($j=$begin; $j -le 2; $j++) {
            if ($j -eq 0) {
                [void][reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint")
                $fileo = [Microsoft.SharePoint.Administration.SPAdministrationWebApplication]::Local.IisSettings.get_Item(0).Path.FullName + "\web.config"
            }
            elseif ($j -eq 1) {
                $fileo = $env:CommonProgramFiles + "\Microsoft Shared\Web Server Extensions\14\WebServices\SecurityToken\web.config"
                if ($flavor -eq "DEBUG") { $fileo = $fileo.replace("Shared", "Shared Debug") }
            }
            else {
                if ($vroot -ne "APP") { $fileo = $env:HomeDrive + "\inetpub\wwwroot\wss\VirtualDirectories\$vroot\web.config" }
            }
    
            $xmlo = [xml](get-content $fileo)
            $perf = $xmlo.CreateElement("clear")
    
            if ($flavor -eq "DEBUG") {
                $ship = $root.config[1].tokens.token[0].value
                $debug = $root.config[1].tokens.token[1].value
                $token = $root.config[0]["system.web"].membership.providers.add[0].type
                $root.config[0]["system.web"].membership.providers.add[0].SetAttribute("type", $token.replace($ship,$debug)) | Out-Null
                $token = $root.config[0]["system.web"].rolemanager.providers.add[0].type
                $root.config[0]["system.web"].rolemanager.providers.add[0].SetAttribute("type", $token.replace($ship,$debug)) | Out-Null
            }
    
            if ($j -eq 0) {
                # Update the CA web config
                if (-not $xmlo.SelectSingleNode("/configuration/connectionStrings")) {
                    $xmlo.configuration["system.web"].membership.ParentNode.RemoveChild($xmlo.configuration["system.web"].membership) | Out-Null
                    $xmlo.configuration["system.web"].roleManager.ParentNode.RemoveChild($xmlo.configuration["system.web"].roleManager) | Out-Null
                    $xmlo.SelectSingleNode("/configuration").AppendChild($xmlo.ImportNode($root.config[0]["connectionStrings"], $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web").AppendChild($xmlo.ImportNode($root.config[0]["system.web"].membership, $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/membership/providers").PrependChild($xmlo.ImportNode($perf, $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web").AppendChild($xmlo.ImportNode($root.config[0]["system.web"].rolemanager, $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/roleManager/providers").PrependChild($xmlo.ImportNode($perf, $true)) | Out-Null
                }
            }
            elseif ($j -eq 1) {
                # Update the STS web config
                if (-not $xmlo.SelectSingleNode("/configuration/system.web")) {
                    $xmlo.SelectSingleNode("/configuration").AppendChild($xmlo.ImportNode($root.config[0]["connectionStrings"], $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration").AppendChild($xmlo.ImportNode($root.config[0]["system.web"], $true)) | Out-Null
                }
            }
            else {
                # Update the FBA web config
                if ($vroot -ne "APP") {
                    if ($type.contains("PPL")) {$provider=1} elseif ($type.contains("SUN")) {$provider=2} elseif ($type.contains("IBM")) {$provider=3} elseif ($type.contains("NVL")) {$provider=4} elseif ($type.contains("SQL")) {$provider=5} else {$provider=0}
                    $xmlo.SelectSingleNode("/configuration").AppendChild($xmlo.ImportNode($root.config[0]["connectionStrings"], $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/membership/providers").PrependChild($xmlo.ImportNode($root.config[0]["system.web"].membership.providers.add[$provider], $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/membership/providers").PrependChild($xmlo.ImportNode($perf, $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/roleManager/providers").PrependChild($xmlo.ImportNode($root.config[0]["system.web"].rolemanager.providers.add[$provider], $true)) | Out-Null
                    $xmlo.SelectSingleNode("/configuration/system.web/roleManager/providers").PrependChild($xmlo.ImportNode($perf, $true)) | Out-Null
                }
            }
            $xmlo.Save($fileo)
        }
    }
    
    function Manage-SnapIns ([int]$action) {
        #The OWSTimer process always causes an update conflict (known bug) while
        #creating multiple web apps; let's temporarily shut it down until we're done
    
        if ($action -eq 1) { Stop-Service "SPTimerV4" }
    
        # We need to do this only if we're running on ISE so check it
        if ($host.name.contains("ISE")) {
            if ($action -eq 1) {
                write-host -Fore Yellow "Detecting host and loading dependent snap-ins..."
                # Add-PSSnapIn WebAdministration (later!)
                Add-PSSnapIn Microsoft.Sharepoint.PowerShell
            }
            else {
                write-host -Fore Yellow "Unloading dependent snap-ins loaded earlier on..."
                # Remove-PSSnapIn WebAdministration (later!)
                Remove-PSSnapIn Microsoft.Sharepoint.PowerShell
            }
        }
        if ($action -eq 0) {Start-Service "SPTimerV4"; write-host -Fore Yellow "`nAll done; if there were errors please research PS database for known issues!`n"}
    }
    
    main
    
  6. Запустите IIS, введя в командной строке INETMGR.

  7. Зайдите на сайт Веб-приложение на основе утверждений в IIS.

  8. В левой области щелкните правой кнопкой мыши Веб-приложение на основе утверждений и выберите команду Изменить привязки.

  9. Выберите https и щелкните Правка.

  10. В разделе Сертификат SSL выберите один из перечисленных сертификатов. Рассмотрите возможность использования самозаверяющего сертификата.

  11. Импортируйте общедоступный сертификат Windows Live ID в папки Локальный компьютер, SharePoint Server 2010 и Доверенные лица.

  12. Выполните сброс IIS и введите в адресной строке URL-адрес сайта.

Предоставление разрешений всем пользователям Windows Live ID, прошедшим проверку подлинности

Чтобы предоставить разрешения всем пользователям Windows Live ID, прошедшим проверку подлинности, используйте инструкции, приведенные в этом разделе.

Предоставление разрешений всем пользователям Windows Live ID, прошедшим проверку подлинности

  1. Откройте созданный сайт SharePoint Server 2010 и выполните вход с учетной записью администратора.

  2. В меню Действия сайта выберите пункт Параметры сайта.

  3. В разделе Пользователи и разрешения выберите Разрешения сайта.

  4. Выберите группу Посетители имя_сайта, где имя_сайта — это имя сайта.

  5. Нажмите кнопку Добавить и затем выберите Добавить пользователей.

  6. В окне Предоставление разрешений щелкните значок обзора.

  7. В диалоговом окне Выбор людей и групп выберите Все пользователи и затем выберите Все пользователи (LiveIDSTS) в панели справа.

  8. Нажмите кнопку Добавить.

  9. Нажмите кнопку ОК.

  10. Убедитесь, что теперь Все пользователи (LiveIDSTS) являются частью группы посетителей. Теперь можно выполнить вход на сайт SharePoint Server 2010 с любыми учетными данными пользователя Live ID.

Об авторе

Бирендра Ачария (Birendra Acharya), старший проектировщик программного обеспечения для MSIT корпорации Майкрософт.

See Also

Other Resources

Общие сведения о WS-Federation (https://go.microsoft.com/fwlink/?linkid=192377&clcid=0x419) (Возможно, на английском языке)