Tuesday, December 20, 2011

Read Credentials from Secure Store Service Programatically in SharePoint 2010

Hello,

If you want to read the credentials set in secure store service programatically, then the below code is helpful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;


namespace ReadSecureStoreCredentials
{
    public static class SecureStoreUtils
    {
        public static Dictionary<string, string> GetCredentials(string applicationID)
        {
            var credentialMap = new Dictionary<string, string>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = SPContext.Current.Site;
                SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                var secureStoreProvider = new SecureStoreProvider { Context = serviceContext };
                using (var credentials = secureStoreProvider.GetCredentials(applicationID))
                {
                    var fields = secureStoreProvider.GetTargetApplicationFields(applicationID);
                    for (var i = 0; i < fields.Count; i++)
                    {
                        var field = fields[i];
                        var credential = credentials[i];
                        var decryptedCredential = ToClrString(credential.Credential);

                        credentialMap.Add(field.Name, decryptedCredential);
                    }
                }
            });
            return credentialMap;
        }

        public static string ToClrString(this SecureString secureString)
        {
            var ptr = Marshal.SecureStringToBSTR(secureString);

            try
            {
                return Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                Marshal.FreeBSTR(ptr);
            }
        }
    }
}


Make sure you have added the following dll's

1. Microsoft.Office.SecureStoreService.dll located at C:\Windows\assembly\GAC_MSIL\Microsoft.Office.SecureStoreService\14.0.0.0__71e9bce111e9429c\Microsoft.Office.SecureStoreService.dll and

2. Microsoft.BusinessData.dll located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.BusinessData.dll

And here is how you make use of the above code to read credentials from secure store service

Dictionary<string, string> SSCredentials = SecureStoreUtils.GetCredentials("SecureStoreId");
string strDU = SSCredentials.ElementAt(0).Value;
int SlashPos = strDU.IndexOf('\\');
this.strDomainName = strDU.Substring(0, SlashPos);
this.strUserName = strDU.Substring(SlashPos + 1, strDU.Length - this.strDomainName.Length - 1);
this.strPassword = SSCredentials.ElementAt(1).Value;


Bye for now :)

7 comments:

  1. Well layed out, clear and precise, thanks

    ReplyDelete
  2. My friend, this post is amazing, thank you very much!

    ReplyDelete
  3. Hi, thanks a lot for the nice post!

    I am trying to read credentials from a sharepoint hosted webservice (wcf).
    I get this error when trying to read:

    Credentials were not found for the current user within the target application . Please set the credentials for the current user.

    Do you have any idea why this might happen?

    Any help is greatly appreciated!

    ReplyDelete
  4. Excellent! Thanks for this - I've been looking at this feature for ages. Followed your instructions and it works a treat!

    ReplyDelete
  5. I am trying to use this code to read the secure store credentials for webpart to execute stored procedure but i am unable to do so. the first part of this code should be in a separate .cs file or in the same .cs file of webpart?

    ReplyDelete
  6. I am getting access denied while using this code. I was able to figure out other errors.

    Please advise.

    Thanks!

    ReplyDelete