Поделиться через


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

Дата последнего изменения: 14 мая 2010 г.

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

В примере кода ниже показывается, как получить учетные данные пользователя с помощью поставщика безопасного хранения по умолчанию.

Необходимые компоненты:

  • Microsoft SharePoint Server 2010

  • Microsoft .NET Framework 3.5

Использование этого примера

  1. Запустите Microsoft Visual Studio, а затем создайте новый проект консольного приложения C#. При создании проекта выберите .NET Framework 3.5.

  2. В меню Вид выберите Страницы свойств, чтобы отобразить свойства проекта.

  3. На вкладке Построение в качестве значения поля Целевая платформа выберите Любой ЦП.

  4. Закройте окно свойств проекта

  5. В обозревателе решений в разделе Ссылки удалите все ссылки проекта кроме System и System.Core.

  6. Добавьте в проект следующие ссылки:

    1. Microsoft.BusinessData;

    2. Microsoft.Office.SecureStoreService;

    3. Microsoft.SharePoint;

    4. System.Web.

  7. Замените код, автоматически созданный в файле Program.cs, на код, приведенный в конце этой процедуры.

  8. Замените значение appId именем конечного приложения безопасного хранения. Обратите внимание, что конечным приложением безопасного хранения, используемым в этом примере, является приложение типа Individual, содержащее следующее: имя пользователя (не имя пользователя Windows), пароль (не пароль Windows) и ПИН-код.

  9. Нажмите клавишу F6, чтобы построить решение.

  10. Нажмите клавиши 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;
        }
   }
} 

См. также

Ссылка

SecureStoreProviderFactory

Create()

ISecureStoreProvider

ISecureStoreServiceContext

SPServiceContext

GetCredentials(String)

SecureStoreCredentialCollection

SecureStoreCredential

CredentialType

SPAdministrationWebApplication