Фрагмент кода. Получение учетных данных пользователя с помощью поставщика безопасного хранения по умолчанию
Дата последнего изменения: 14 мая 2010 г.
Применимо к: SharePoint Server 2010
В примере кода ниже показывается, как получить учетные данные пользователя с помощью поставщика безопасного хранения по умолчанию.
Необходимые компоненты:
Microsoft SharePoint Server 2010
Microsoft .NET Framework 3.5
Использование этого примера
Запустите Microsoft Visual Studio, а затем создайте новый проект консольного приложения C#. При создании проекта выберите .NET Framework 3.5.
В меню Вид выберите Страницы свойств, чтобы отобразить свойства проекта.
На вкладке Построение в качестве значения поля Целевая платформа выберите Любой ЦП.
Закройте окно свойств проекта
В обозревателе решений в разделе Ссылки удалите все ссылки проекта кроме System и System.Core.
Добавьте в проект следующие ссылки:
Microsoft.BusinessData;
Microsoft.Office.SecureStoreService;
Microsoft.SharePoint;
System.Web.
Замените код, автоматически созданный в файле Program.cs, на код, приведенный в конце этой процедуры.
Замените значение appId именем конечного приложения безопасного хранения. Обратите внимание, что конечным приложением безопасного хранения, используемым в этом примере, является приложение типа Individual, содержащее следующее: имя пользователя (не имя пользователя Windows), пароль (не пароль Windows) и ПИН-код.
Нажмите клавишу F6, чтобы построить решение.
Нажмите клавиши CTRL+F5, чтобы запустить пример.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace Microsoft.SDK.Sharepoint.Samples
{
class Program
{
static void Main(string[] args)
{
// Get the default Secure Store Service provider.
ISecureStoreProvider provider = SecureStoreProviderFactory.Create();
if (provider == null)
{
throw new InvalidOperationException("Unable to get an ISecureStoreProvider");
}
ISecureStoreServiceContext providerContext = provider as ISecureStoreServiceContext;
providerContext.Context = SPServiceContext.GetContext(GetCentralAdminSite());
// Create the variables to hold the credentials.
string userName = null;
string password = null;
string pin = null;
// Specify a valid target application ID for the Secure Store.
string appId = "mySecureStoreTargetApplication";
try
{
// Because we are getting the credentials in the using block, all the credentials that we get
// will be disposed after the using block. If you need to cache the credentials, do not
// use the using block, and dispose the credentials when you are finished.
//
// In the following block, we are looking for the first user name, password, and pin
// credentials in the collection.
using (SecureStoreCredentialCollection creds = provider.GetCredentials(appId))
{
// Secure Store Service will not return null. It may throw a SecureStoreServiceException,
// but this may not be true for other providers.
Debug.Assert(creds != null);
if (creds != null)
{
foreach (SecureStoreCredential cred in creds)
{
if (cred == null)
{
// Secure Store Service will not return null credentials, but this may not be true for other providers.
continue;
}
switch (cred.CredentialType)
{
case SecureStoreCredentialType.UserName:
if (userName == null)
{
userName = GetStringFromSecureString(cred.Credential);
}
break;
case SecureStoreCredentialType.Password:
if (password == null)
{
password = GetStringFromSecureString(cred.Credential);
}
break;
case SecureStoreCredentialType.Pin:
if (pin == null)
{
pin = GetStringFromSecureString(cred.Credential);
}
break;
}
}
}
}
if (userName == null || password == null || pin == null)
{
throw new InvalidOperationException("Unable to get the credentials");
}
// Use the credentials.
//
// Note that it is not a secure programming practice to print credential information, but this code example
// prints the credentials to the console for testing purposes.
Console.WriteLine("User Name: " + userName);
Console.WriteLine("Password : " + password);
Console.WriteLine("Pin : " + pin);
}
catch (SecureStoreException e)
{
Console.WriteLine(e.Message);
throw;
}
}
private static string GetStringFromSecureString(SecureString secStr)
{
if (secStr == null)
{
return null;
}
IntPtr pPlainText = IntPtr.Zero;
try
{
pPlainText = Marshal.SecureStringToBSTR(secStr);
return Marshal.PtrToStringBSTR(pPlainText);
}
finally
{
if (pPlainText != IntPtr.Zero)
{
Marshal.FreeBSTR(pPlainText);
}
}
}
public static SPSite GetCentralAdminSite()
{
SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;
if (adminWebApp == null)
{
throw new InvalidProgramException("Unable to get the admin web app");
}
SPSite adminSite = null;
Uri adminSiteUri = adminWebApp.GetResponseUri(SPUrlZone.Default);
if (adminSiteUri != null)
{
adminSite = adminWebApp.Sites[adminSiteUri.AbsoluteUri];
}
else
{
throw new InvalidProgramException("Unable to get Central Admin Site.");
}
return adminSite;
}
}
}