Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Artigo original publicado em 20 de março de 2011, domingo
Já ouvi esta pergunta algumas vezes, e foi por isso que quis encontrar programaticamente quais provedores de declarações estão sendo usados por meu aplicativo Web. Esta pergunta geralmente é feita para saber quais SPTrustedIdentityTokenIssuers estão sendo usados, mas o método que demonstrarei revela estes e outros provedores de declarações personalizados que não são habilitados por padrão (porque se estivessem, seriam usados em todos os lugares).
A primeira coisa a fazer é entender que se você estiver se perguntando o que está habilitado para um aplicativo Web, está pensando errado (e é provavelmente que o pessoal tem considerado difícil achar essas informações). Seus provedores de declarações serão aplicados no nível de zona, e não no nível de aplicativo. Assim, em uma URL do SharePoint, como descobrimos essa informação?
Para começar, obtenha um novo SPSite baseado na URL na qual está interessado:
using (SPSite theSite = new SPSite("https://someUrl"))
{
…
}
Quando já tiver o objeto SPSite, você pode obter o aplicativo Web e a zona:
//get the web app
SPWebApplication wa = theSite.WebApplication;
//get the zone for the site
SPUrlZone theZone = theSite.Zone;
Com essas informações, você pode obter SPIisSettings para a zona, que é onde a maior parte das coisas boas reside:
//get the settings associated with the zone
SPIisSettings theSettings = wa.GetIisSettingsWithFallback(theZone);
Uma vez de posse das informações de zona, posso obter seus provedores de autenticação e de declarações. Eles são encontrados nestas duas propriedades: ClaimsAuthenticationProviders e ClaimsProviders. Agora lembre-se de que cada ClaimsAuthenticationProvider possui somente um subconjunto muito pequeno das informações que você obtém ao fazer algo como Get-SPTrustedIdentityTokenIssuers no PowerShell. Se realmente quiser chegar ao núcleo do objeto subjacente, você precisa pegar ClaimsAuthenticationProvider e obter SPTrustedLoginProvider dele. Felizmente isso não é muito difícil. Veja um exemplo no qual estou basicamente consultando uma lista de SPTrustedLoginProviders usando LINQ; observe que, neste exemplo, estou interessado apenas nos provedores de declarações SAML (A.K.A. SPTrustedIdentityTokenIssuer):
//get the token service manager so we can retrieve the appropriate
//trusted login provider
SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local;
//get the list of authentication providers associated with the zone
foreach (SPAuthenticationProvider prov in theSettings.ClaimsAuthenticationProviders)
{
//make sure the provider we're looking at is a SAML claims provider
if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
{
//get the SPTrustedLoginProvider using the DisplayName
var lp =
from SPTrustedLoginProvider spt in
sptMgr.TrustedLoginProviders
where spt.DisplayName == prov.DisplayName
select spt;
//there should only be one match, so retrieve that
if ((lp != null) && (lp.Count() > 0))
{
//get the login provider
SPTrustedLoginProvider loginProv = lp.First();
}
}
}
Para que fique completo, vou colar o bloco de códigos inteiro abaixo. Neste cenário específico eu estava procurando por todos os SPTrustedIdentityTokenIssuers associados a uma zona, e para cada um eu estava criando uma string com o nome do provedor e a URL para a qual você seria redirecionado para autenticação ao usar aquele provedor.
using (SPSite theSite = new SPSite("https://someUrl"))
{
//get the web app
SPWebApplication wa = theSite.WebApplication;
//get the zone for the site
SPUrlZone theZone = theSite.Zone;
//get the settings associated with the zone
SPIisSettings theSettings = wa.GetIisSettingsWithFallback(theZone);
//if this isn't a claims auth site then bail out
if (!theSettings.UseTrustedClaimsAuthenticationProvider)
{
MessageBox.Show("This is not a SAML claims auth site");
return;
}
//clear the list of providers out
ProviderLst.Items.Clear();
//get the token service manager so we can retrieve the appropriate
//trusted login provider
SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local;
//get the list of authentication providers associated with the zone
foreach (SPAuthenticationProvider prov in
theSettings.ClaimsAuthenticationProviders)
{
//make sure the provider we're looking at is a SAML claims provider
if (prov.GetType() ==
typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
{
//get the SPTrustedLoginProvider using the DisplayName
var lp =
from SPTrustedLoginProvider spt in
sptMgr.TrustedLoginProviders
where spt.DisplayName == prov.DisplayName
select spt;
//there should only be one match, so retrieve that
if ((lp != null) && (lp.Count() > 0))
{
//get the login provider
SPTrustedLoginProvider loginProv = lp.First();
//get the login info
string provInfo = prov.DisplayName + " - " +
loginProv.ProviderUri.ToString();
//add the login info to the list
ProviderLst.Items.Add(provInfo);
}
}
}
}
Esta é uma postagem de blog traduzida. Leia o artigo original sobre How To Get All Claims Providers Associated with a Web Application in SharePoint 2010