Skip to content

Instantly share code, notes, and snippets.

@Marfusios
Last active August 29, 2015 14:09
Show Gist options
  • Save Marfusios/ee27f8911161dfd2f202 to your computer and use it in GitHub Desktop.
Save Marfusios/ee27f8911161dfd2f202 to your computer and use it in GitHub Desktop.
// Saving credentials into Windows credentials storage
// Helper class for CredentialManagement library (http://www.nuget.org/packages/CredentialManagement/)
// It loads the library dynamically, so you can add or remove it at runtime
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace MyApp.Credentials
{
static class CredentialsManager
{
private const string TARGET_PREFIX = "MyApp@";
private const string CREDENTIAL_LIBRARY_NAME = "CredentialManagement";
private static readonly string PATH_TO_EXECUTION_FOLDER = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static readonly string PATH_TO_DLL = Path.Combine(PATH_TO_EXECUTION_FOLDER, CREDENTIAL_LIBRARY_NAME + ".dll");
private static bool _alreadyTriedLoadCredentialLibrary;
public static bool IsCredentialsLibraryLoaded
{
get { return getCredentialLibrary() != null; }
}
public static bool StoreCredentials(UserCredentials user)
{
try
{
var asm = getCredentialLibrary();
if (asm == null)
return false;
var credentialType = asm.GetType("CredentialManagement.Credential");
var persistanceEnumType = asm.GetType("CredentialManagement.PersistanceType");
dynamic cm = Activator.CreateInstance(credentialType);
cm.Target = TARGET_PREFIX + user.Key;
cm.Username = user.Username;
cm.Password = user.Password;
// ReSharper disable once RedundantCast - Must cast to dynamic (otherwise it throws exception)
cm.PersistanceType = (dynamic)Enum.Parse(persistanceEnumType, "Enterprise");
return cm.Save();
}
catch
{
return false;
}
}
public static UserCredentials RestoreCredentials(string key)
{
try
{
var asm = getCredentialLibrary();
if (asm == null)
return null;
var type = asm.GetType("CredentialManagement.Credential");
dynamic cm = Activator.CreateInstance(type);
cm.Target = TARGET_PREFIX + key;
if (!cm.Exists())
return null;
cm.Load();
return new UserCredentials(cm.Username, cm.Password, key);
}
catch
{
return null;
}
}
private static Assembly getCredentialLibrary()
{
var loaded =
AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(x => x.FullName.Contains(CREDENTIAL_LIBRARY_NAME));
if (loaded == null && !_alreadyTriedLoadCredentialLibrary)
{
try
{
Assembly.LoadFile(PATH_TO_DLL);
}
catch { }
_alreadyTriedLoadCredentialLibrary = true;
return getCredentialLibrary();
}
return loaded;
}
}
class UserCredentials
{
public string Username { get; set; }
public string Password { get; set; }
public string Key { get; set; }
public UserCredentials(string username, string password, string key)
{
Username = username;
Password = password;
Key = key;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment