06 January 2012

Retrieving Passwords from Managed Accounts in SharePoint 2010 for C#

I was looking for a way to retrieve a password from a managed account when I ran into a post titled How to: Get Your Managed Account Passwords When They are Changed Automatically by SharePoint 2010 by Jason Himmelstein.  It was written for PowerShell and I needed in C#, so I figured I would post the converted code in case anyone was looking for the same thing.  You will need to have the following using statements:

using System.Runtime.InteropServices;
using Microsoft.SharePoint.Administration;

Then you can use the following code to retrieve the managed password:

var managedAccounts = new SPFarmManagedAccountCollection(SPFarm.Local);
foreach (SPManagedAccount managedAccount in managedAccounts)
{ 
  var securePassword = (SPEncryptedString)managedAccount
    .GetType()
    .GetField("m_Password", 
      System.Reflection.BindingFlags.GetField |
      System.Reflection.BindingFlags.Instance |
      System.Reflection.BindingFlags.NonPublic)
    .GetValue(managedAccount);

  var intptr = System.IntPtr.Zero;
  var unmanagedString = Marshal.
    SecureStringToGlobalAllocUnicode(securePassword.SecureStringValue);

  var unsecureString = Marshal.PtrToStringUni(unmanagedString);
  Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); 

  //Do something with unsecureString
}

One caveat to this is that you must be running as a Farm Administrator for the code to succeed.  Otherwise you will get an error about accessing the registry.  It is also relying on reflection to retrieve a non-public internal field, so as my friend Jeff Burt was quick to point out, Microsoft could change it at any time and break this code.  Probably not good for production code.

Keep up to date with Simple-Talk

For more articles like this delivered fortnightly, sign up to the Simple-Talk newsletter

This post has been viewed 3861 times – thanks for reading.

  • Rate
    [Total: 0    Average: 0/5]
  • Share

Damon Armstrong

Damon Armstrong is a Senior Engineering Team Lead with GimmalSoft in Dallas, Texas, and author of Pro ASP.NET 2.0 Website Programming. He specializes in Microsoft technologies with a focus on SharePoint and ASP.NET. When not staying up all night coding, he can be found playing disc golf, softball, working on something for Carrollton Young Life, or recovering from staying up all night coding.

View all articles by Damon Armstrong