다음을 통해 공유


Code Snippet: Get User Credentials Using the Default Secure Store Provider

Applies to: SharePoint Server 2010

The following code example demonstrates how to get user credentials by using the default secure store provider.

Prerequisites:

  • Microsoft SharePoint Server 2010

  • Microsoft .NET Framework 3.5

To use this example

  1. Start Microsoft Visual Studio, and then create a new C# Console Application project. Select .NET Framework 3.5 when you create the project.

  2. From the View menu, select Property Pages to bring up the project properties.

  3. On the Build tab, for the Platform target, select Any CPU.

  4. Close the project properties window.

  5. In Solution Explorer, under References, remove all project references except for System and System.Core.

  6. Add the following references to the project:

    1. Microsoft.BusinessData

    2. Microsoft.Office.SecureStoreService

    3. Microsoft.SharePoint

    4. System.Web

  7. Replace the auto-generated code in Program.cs with the code listed at the end of this procedure.

  8. Replace the value of appId with the name of your Secure Store target application. Note that the secure score target application that is used in this example is an Individual type application that contains the following: User name (not the Windows user name), Password (not the Windows password), and a    PIN.

  9. Press F6 to build the solution.

  10. Press Ctrl+F5 to run the sample.

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;
        }
   }
} 

See Also

Reference

SecureStoreProviderFactory

Create()

ISecureStoreProvider

ISecureStoreServiceContext

SPServiceContext

GetCredentials(String)

SecureStoreCredentialCollection

SecureStoreCredential

CredentialType

SPAdministrationWebApplication