private static NetworkCredential GetManagedAccountCredential(string managedAccount)
{
NetworkCredential result = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPFarmManagedAccountCollection accounts = new SPFarmManagedAccountCollection(SPFarm.Local);
SPManagedAccount account = accounts.FindOrCreateAccount(managedAccount);
string[] usernameSplit = account.Username.Split('\\');
string username = usernameSplit[1];
string domain = usernameSplit[0];
var securePassword = (SPEncryptedString)account
.GetType()
.GetField("m_Password",
System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic)
.GetValue(account);
// TODO - remove these 3 lines when .Net 4.0 is available and we can create NetworkCredential with SecureString
var intptr = System.IntPtr.Zero;
var unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword.SecureStringValue);
var password = Marshal.PtrToStringUni(unmanagedString);
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
result = new NetworkCredential(username, password, domain);
password = null;
});
}
catch (Exception ex)
{
Logging.LogException("GetManagedAccountCredential", ex);
}
return result;
}
No comments:
Post a Comment