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 :)