Share via


Provedores de Autenticação de Windows <provedores>

Visão geral

A coleção <providers> do elemento <windowsAuthentication> define a lista de provedores de autenticação que são usados com o módulo de autenticação do Windows do IIS (Serviços de Informações da Internet) 7. Essa lista de provedores não pode ser estendida e, por padrão, contém apenas duas entradas:

  • Negociar - Esse provedor tentará usar o Kerberos para autenticação se estiver disponível.
  • NTLM - Este provedor tentará usar a Autenticação Integrada do Windows para autenticação.

Compatibilidade

Versão Observações
IIS 10.0 O elemento <providers> não foi modificado no IIS 10.0.
IIS 8.5 O elemento <providers> não foi modificado no IIS 8.5.
IIS 8.0 O elemento <providers> não foi modificado no IIS 8.0.
IIS 7.5 O elemento <providers> não foi modificado no IIS 7.5.
IIS 7.0 O elemento <providers> do elemento <windowsAuthentication> foi introduzido no IIS 7.0.
IIS 6,0 A coleção<providers> substitui a propriedade de metabase NTAuthenticationProviders do IIS 6.0.

Instalação

A instalação padrão do IIS 7 e posterior não inclui o serviço de função autenticação do Windows. Para usar a autenticação do Windows no IIS, você deve instalar o serviço de função, desabilitar a autenticação anônima para seu site ou aplicativo e habilitar a autenticação do Windows para o site ou aplicativo.

Observação

Depois de instalar o serviço de função, o IIS 7 confirma as seguintes definições de configuração para o arquivo ApplicationHost.config.

<windowsAuthentication enabled="false" />

Windows Server 2012 R2 ou Windows Server 2012

  1. Na barra de tarefas, clique em Gerenciador do Servidor.
  2. No Gerenciador do Servidor, clique no menu Gerenciar e clique em Adicionar Funções e Recursos.
  3. No assistente Adicionar Funções e Recursos, clique em Avançar. Selecione o tipo de instalação e clique em Avançar. Selecione o servidor de destino e clique em Avançar.
  4. Na página Funções de Servidor, expanda Servidor Web (IIS), Servidor Web, expanda Segurança e selecione Autenticação do Windows. Clique em Avançar.
    Screenshot of the Windows Authentication option being selected and highlighted.
  5. Na página Selecionar recursos, clique em Avançar.
  6. Na página Confirmar seleções de instalação, clique em Instalar.
  7. Na página Resultados , clique em Fechar.

Windows 8 ou Windows 8.1

  1. Na tela Iniciar, mova o ponteiro até o canto inferior esquerdo, clique com o botão direito do mouse no botão Iniciar e clique em Painel de Controle.
  2. Em Painel de Controle, clique em Programas e Recursos e clique em Ativar ou desativar recursos do Windows.
  3. Expanda Serviços de Informações da Internet, expanda Serviços da World Wide Web, expanda Segurança e, em seguida, selecione Autenticação do Windows.
    Screenshot of the Windows Authentication folder being selected and highlighted.
  4. Clique em OK.
  5. Clique em Fechar.

Windows Server 2008 R2 ou Windows Server 2008

  1. Na barra de tarefas, clique em Iniciar, vá para Ferramentas Administrativas e clique em Gerenciador do Servidor.
  2. No painel de hierarquia do Gerenciador do Servidor, expanda Funções e clique em Servidor Web (IIS).
  3. No painel Servidor Web (IIS), role até a seção Serviços de Função e clique em Adicionar Serviços de Função.
  4. Na página Selecionar Serviços de Função do Assistente para Adicionar Serviços de Função, selecione Autenticação do Windows e clique em Avançar.
    Screenshot of the Add Role Services Wizard showing the selected and highlighted Windows Authentication option.
  5. Na página Confirmar Seleções de Instalação, clique em Instalar.
  6. Na página Resultados , clique em Fechar.

Windows Vista ou Windows 7

  1. Na barra de tarefas, clique em Iniciar e, depois, em Painel de Controle.
  2. Em Painel de Controle, clique em Programas e Recursos e clique em Ativar ou desativar Recursos do Windows.
  3. Expanda Serviços de Informações da Internet e, em seguida, Serviços World Wide Web e, em seguida, Segurança.
  4. Selecione Autenticação do Windows e clique em OK.
    Screenshot of the Security folder being expanded, showing the Windows Authentication folder being selected and highlighted.

Instruções

Não há nenhuma interface de usuário para provedores de autenticação do Windows para o IIS 7. Para obter exemplos de como modificar a lista de provedores de autenticação do Windows programaticamente, consulte a seção Exemplos de Código deste documento.

Configuração

Atributos

Nenhum.

Elementos filho

Elemento Descrição
add Elemento opcional.

Adiciona um provedor de segurança à coleção de provedores. A autenticação do Windows requer pelo menos um provedor.
remove Elemento opcional.

Remove uma referência a um provedor de segurança da coleção de provedores.
clear Elemento opcional.

Remove todas as referências a provedores da coleção de provedores.

Exemplo de configuração

O elemento <windowsAuthentication> padrão a seguir é configurado no arquivo raiz ApplicationHost.config no IIS 7.0 e desabilita a autenticação do Windows por padrão. Ele também define os dois provedores de autenticação do Windows para o IIS 7.0.

<windowsAuthentication enabled="false">
   <providers>
      <add value="Negotiate" />
      <add value="NTLM" />
   </providers>
</windowsAuthentication>

O exemplo a seguir habilita a autenticação do Windows e desabilita a autenticação anônima para um site chamado Contoso.

<location path="Contoso">
   <system.webServer>
      <security>
         <authentication>
            <anonymousAuthentication enabled="false" />
            <windowsAuthentication enabled="true" />
         </authentication>
      </security>
   </system.webServer>
</location>

Exemplo de código

Os exemplos de código a seguir habilitarão a autenticação do Windows e removerão o provedor Negotiate de um site chamado Contoso.

AppCmd.exe

appcmd.exe set config "Contoso" -section:system.webServer/security/authentication/windowsAuthentication /enabled:"True" /commit:apphost

appcmd.exe set config "Contoso" -section:system.webServer/security/authentication/windowsAuthentication /-"providers.[value='Negotiate']" /commit:apphost

Observação

Defina o parâmetro commit para apphost quando usar AppCmd.exe para definir essas configurações. Isso confirma as definições de configuração para a seção de local apropriado no arquivo ApplicationHost.config.

C#

using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample
{
   private static void Main()
   {
      using (ServerManager serverManager = new ServerManager())
      {
         Configuration config = serverManager.GetApplicationHostConfiguration();
         ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "Contoso");
         windowsAuthenticationSection["enabled"] = true;

         ConfigurationElementCollection providersCollection = windowsAuthenticationSection.GetCollection("providers");
         ConfigurationElement addElement = FindElement(providersCollection, "add", "value", @"Negotiate");

         if (addElement == null) throw new InvalidOperationException("Element not found!");
         providersCollection.Remove(addElement);

         serverManager.CommitChanges();
      }
   }

   private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
   {
      foreach (ConfigurationElement element in collection)
      {
         if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
         {
            bool matches = true;
            for (int i = 0; i < keyValues.Length; i += 2)
            {
               object o = element.GetAttributeValue(keyValues[i]);
               string value = null;
               if (o != null)
               {
                  value = o.ToString();
               }
               if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
               {
                  matches = false;
                  break;
               }
            }
            if (matches)
            {
               return element;
            }
         }
      }
      return null;
   }
}

VB.NET

Imports System
Imports System.Text
Imports Microsoft.Web.Administration

Module Sample
   Sub Main()
      Dim serverManager As ServerManager = New ServerManager
      Dim config As Configuration = serverManager.GetApplicationHostConfiguration
      Dim windowsAuthenticationSection As ConfigurationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "Contoso")
      windowsAuthenticationSection("enabled") = True

      Dim providersCollection As ConfigurationElementCollection = windowsAuthenticationSection.GetCollection("providers")
      Dim addElement As ConfigurationElement = FindElement(providersCollection, "add", "value", "Negotiate")

      If (addElement Is Nothing) Then
         Throw New InvalidOperationException("Element not found!")
      End If
      providersCollection.Remove(addElement)

      serverManager.CommitChanges()
   End Sub

   Private Function FindElement(ByVal collection As ConfigurationElementCollection, ByVal elementTagName As String, ByVal ParamArray keyValues() As String) As ConfigurationElement
      For Each element As ConfigurationElement In collection
         If String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase) Then
            Dim matches As Boolean = True
            Dim i As Integer
            For i = 0 To keyValues.Length - 1 Step 2
               Dim o As Object = element.GetAttributeValue(keyValues(i))
               Dim value As String = Nothing
               If (Not (o) Is Nothing) Then
                  value = o.ToString
               End If
               If Not String.Equals(value, keyValues((i + 1)), StringComparison.OrdinalIgnoreCase) Then
                  matches = False
                  Exit For
               End If
            Next
            If matches Then
               Return element
            End If
         End If
      Next
      Return Nothing
   End Function


End Module

JavaScript

var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST";
var windowsAuthenticationSection = adminManager.GetAdminSection("system.webServer/security/authentication/windowsAuthentication", "MACHINE/WEBROOT/APPHOST/Contoso");
windowsAuthenticationSection.Properties.Item("enabled").Value = true;

var providersCollection = windowsAuthenticationSection.ChildElements.Item("providers").Collection;
var addElementPos = FindElement(providersCollection, "add", ["value", "Negotiate"]);
if (addElementPos == -1) throw "Element not found!";
providersCollection.DeleteElement(addElementPos);

adminManager.CommitChanges();

function FindElement(collection, elementTagName, valuesToMatch) {
   for (var i = 0; i < collection.Count; i++) {
      var element = collection.Item(i);
      if (element.Name == elementTagName) {
         var matches = true;
         for (var iVal = 0; iVal < valuesToMatch.length; iVal += 2) {
            var property = element.GetPropertyByName(valuesToMatch[iVal]);
            var value = property.Value;
            if (value != null) {
               value = value.toString();
            }
            if (value != valuesToMatch[iVal + 1]) {
               matches = false;
               break;
            }
         }
         if (matches) {
            return i;
         }
      }
   }
   return -1;
}

VBScript

Set adminManager = WScript.CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"
Set windowsAuthenticationSection = adminManager.GetAdminSection("system.webServer/security/authentication/windowsAuthentication", "MACHINE/WEBROOT/APPHOST/Contoso")
windowsAuthenticationSection.Properties.Item("enabled").Value = True

Set providersCollection = windowsAuthenticationSection.ChildElements.Item("providers").Collection
addElementPos = FindElement(providersCollection, "add", Array("value", "Negotiate"))

If (addElementPos = -1) Then
   WScript.Echo "Element not found!"
   WScript.Quit
End If
providersCollection.DeleteElement(addElementPos)

adminManager.CommitChanges()

Function FindElement(collection, elementTagName, valuesToMatch)
   For i = 0 To CInt(collection.Count) - 1
      Set element = collection.Item(i)
      If element.Name = elementTagName Then
         matches = True
         For iVal = 0 To UBound(valuesToMatch) Step 2
            Set property = element.GetPropertyByName(valuesToMatch(iVal))
            value = property.Value
            If Not IsNull(value) Then
               value = CStr(value)
            End If
            If Not value = CStr(valuesToMatch(iVal + 1)) Then
               matches = False
               Exit For
            End If
         Next
         If matches Then
            Exit For
         End If
      End If
   Next
   If matches Then
      FindElement = i
   Else
      FindElement = -1
   End If
End Function