Responsive Ads Here

Friday, October 17, 2014

How to read the credentials from secure store service in SharePoint

We know that Secure store service is a service which will store the credentials in secure way. we will use this service in SharePoint commonly in business connectivity services (BCS) and Excel and visio service.
I came across a scenario in my project how to read the credentials from secure store service using code.
 Please find the below code snippet which will give the clear understanding how to do it.

/// 
/// Method to read the credentials from secure store service
/// 
/// SPSite
/// Secure Store Application Id
/// Credentials
public static string[] GetCredentialsFromSecureStoreService(SPSite Site, string AppId)
{
  string[] Credentials = new String[2];
  try
  {
    using (SPServiceContextScope scope = new Microsoft.SharePoint.SPServiceContextScope(SPServiceContext.GetContext(Site)))
    {
        string Provider = ExchangeSyncConstants.Miscellaneous.SecureStoreServiceProvider;
        Type ProviderType = Type.GetType(Provider);
        ISecureStoreProvider provider = (ISecureStoreProvider)Activator.CreateInstance(ProviderType);
        string appTargetName = AppId;
        SecureStoreCredentialCollection credentials = provider.GetCredentials(appTargetName);
        foreach (ISecureStoreCredential cred in credentials)
        {
           if (cred.CredentialType == SecureStoreCredentialType.UserName)
           {
             Credentials[0] = ParseString(cred.Credential);
           }
           else if (cred.CredentialType == SecureStoreCredentialType.Password)
           {
             Credentials[1] = ParseString(cred.Credential);
           }
        }
    }
 }
 catch (Exception ex)
 {
               
 }     
 return Credentials;
}

/// 
/// Parse the string
/// 
/// Seucre String
/// string
public static string ParseString(System.Security.SecureString secureString)
{
  string outStr = null;
  IntPtr intPtr = IntPtr.Zero;

  try
  {
     intPtr = Marshal.SecureStringToBSTR(secureString);
     outStr = Marshal.PtrToStringBSTR(intPtr);
  }
  catch (Exception ex)
  {
                
  } 
  finally
  {
    Marshal.FreeBSTR(intPtr);
  }

   return outStr;
}

Below code snippet will give a idea how to use it.

string[] credentials = aaa.GetCredentialsFromSecureStoreService(site, secureStoreAppName);
 if (credentials != null && credentials.Length == 2)
 {
   userName = credentials[0];
   password = credentials[1];
                          
}

Source : http://www.ashokraja.me/tips/How-to-read-credentials-from-Secure-Store-Service-Application-in-SharePoint

1 comment: