Monday 9 September 2013

Get Credentials from Secure Store AppllicationID - Code Snippet




Private enum SecureStoreCredentials { Username, Password, LoginUrl}

Private void SomeMethod()
{

Dictionary<SecureStoreCredentials, string> credentialMapDocuSign = helper_GetSecureStoreCredentials("ApplicationId");

string value = string.Empty;
string username = string.Empty;
string password = string.Empty;
string url = string.Empty;

if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.Username, out value))
{
        username = value;
}
if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.Password, out value))
{
        password = value;
}           
if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.LoginUrl, out value))
{
       url = value;
}

}


private Dictionary<SecureStoreCredentials, string> helper_GetSecureStoreCredentials(string applicationid)
{
try

{
Dictionary<SecureStoreCredentials, string> credentialMap = new Dictionary<SecureStoreCredentials, string>();
//get handle to secure store
SecureStoreProvider prov = new SecureStoreProvider();
//get the service context this code is running under
SPServiceContext context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default); //SPServiceContext.GetContext(web.Site);
prov.Context = context;
//get the credentials from the secure store
SecureStoreCredentialCollection cc = prov.GetCredentials(applicationid);

foreach (SecureStoreCredential c in cc)
{
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(c.Credential);

string sDecrypString = System.Runtime.InteropServices.Marshal.PtrToStringUni(ptr);

switch (c.CredentialType)
{
case SecureStoreCredentialType.WindowsUserName:

credentialMap.Add(
SecureStoreCredentials.Username, sDecrypString);

break;

case SecureStoreCredentialType.WindowsPassword:

credentialMap.Add(
SecureStoreCredentials.Password, sDecrypString);

break;

case SecureStoreCredentialType.Generic:

credentialMap.Add(
SecureStoreCredentials.LoginUrl, sDecrypString);

break; 


}

return credentialMap;

}
catch (Exception ex)
{
throw ex;

}

}
 

No comments:

Post a Comment