代码段:使用默认安全存储提供程序获取用户凭据

上次修改时间: 2010年5月14日

适用范围: SharePoint Server 2010

以下代码示例演示如何通过使用默认安全存储提供程序来获取用户凭据。

先决条件:

  • Microsoft SharePoint Server 2010

  • Microsoft .NET Framework 3.5

使用此示例

  1. 启动 Microsoft Visual Studio,然后创建新的 C# 控制台应用程序项目。创建项目时选择".NET Framework 3.5"。

  2. 从"视图"菜单中,选择"属性页"以显示项目属性。

  3. 在"生成"选项卡上,为"目标平台"选择"任何 CPU"。

  4. 关闭项目属性窗口。

  5. 在"解决方案资源管理器"中的"引用"下,删除除 SystemSystem.Core 之外的所有项目引用。

  6. 向项目中添加以下引用:

    1. Microsoft.BusinessData

    2. Microsoft.Office.SecureStoreService

    3. Microsoft.SharePoint

    4. System.Web

  7. 用此过程结尾处列出的代码替换 Program.cs 中自动生成的代码。

  8. 将 appId 的值替换为安全存储目标应用程序的名称。请注意,此示例中使用的安全存储目标应用程序是一个 Individual 类型应用程序,它包含:用户名(非 Windows 用户名)、密码(非 Windows 密码)和 PIN。

  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