using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;
using Microsoft.SharePoint.Administration;
using System.Security;
using Microsoft.SharePoint.Administration.Claims;
using System.Globalization;
using Microsoft.SharePoint.Utilities;
using System.Security.Principal;
using Microsoft.Office.Server.Diagnostics;
using System.Web;
namespace sharepoint.util
{
public class SecureStoreCredentialLib
{
private const string SYSTEMACCOUNT = @"domain\\ishareadmin";
/// <summary>
/// Get DB Connection that store in Security store. You should add a Generic field to save your DB Instance.
/// </summary>
/// <param name="CredentialName"></param>
/// <returns></returns>
public string GetConnectionString(string CredentialName)
{
var connection = string.Empty;
var username = string.Empty;
var password = string.Empty;
var dbinstance = string.Empty;
SecureStoreCredentialCollection credentials = null;
SPSecurity.RunWithElevatedPrivileges(() =>
{
SPContext.Current.Web.AllowUnsafeUpdates = true;
var adminUser = SPContext.Current.Web.EnsureUser(SYSTEMACCOUNT);
SPContext.Current.Web.AllowUnsafeUpdates = false;
using (var site = new SPSite(SPContext.Current.Site.ID, adminUser.UserToken))
{
var provider = new SecureStoreProvider();
var context = SPServiceContext.GetContext(site);
provider.Context = context;
credentials = provider.GetCredentials(CredentialName);
}
});
if (credentials != null)
{
foreach (SecureStoreCredential sc in credentials)
{
switch (sc.CredentialType)
{
case SecureStoreCredentialType.Generic:
dbinstance = SecureStoreCredentialLib.ToClrString(sc.Credential);
break;
case SecureStoreCredentialType.Key:
break;
case SecureStoreCredentialType.Password:
password = SecureStoreCredentialLib.ToClrString(sc.Credential);
break;
case SecureStoreCredentialType.Pin:
break;
case SecureStoreCredentialType.UserName:
username = SecureStoreCredentialLib.ToClrString(sc.Credential);
break;
case SecureStoreCredentialType.WindowsPassword:
break;
case SecureStoreCredentialType.WindowsUserName:
break;
default:
break;
}
}
connection = string.Format(
"Data Source={0};Initial Catalog=iShare2_SiteInfo;User ID={1};Password={2};Persist Security Info=True;",
dbinstance,
username,
password
);
}
else
{
throw new Exception("Credentials is null. Cannot get credentials.");
}
return connection;
}
public SecureStoreCredentialCollection GetCredentials(string targetApplicationID)
{
SecureStoreCredentialCollection credentials = null;
var iss = GetISecureStore();
var app = iss.GetApplication(targetApplicationID);
switch (app.Type)
{
case TargetApplicationType.Group:
case TargetApplicationType.Individual:
credentials = iss.GetCredentials(targetApplicationID);
break;
case TargetApplicationType.GroupWithTicketing:
case TargetApplicationType.IndividualWithTicketing:
//Didn't test...
var ticket = iss.IssueTicket();
credentials = iss.RedeemTicket(targetApplicationID, ticket);
break;
case TargetApplicationType.RestrictedGroup:
case TargetApplicationType.RestrictedIndividual:
break;
default:
break;
}
return credentials;
}
public void AddCredentials(string userName, string userPassword, string DBInstance, string targetApplicationID, string targetApplicationContactEmail)
{
CreateTargetApplication(targetApplicationID, targetApplicationContactEmail);
var iss = GetISecureStore();
var applicationFields = iss.GetApplicationFields(targetApplicationID);
var creds = new List<ISecureStoreCredential>(applicationFields.Count);
var ssClaims = iss.GetApplicationAdministratorClaims(targetApplicationID);
using (var credentials = new SecureStoreCredentialCollection(creds))
{
foreach (var ssClaim in ssClaims)
{
foreach (var taf in applicationFields)
{
switch (taf.CredentialType)
{
case SecureStoreCredentialType.Generic:
creds.Add(new SecureStoreCredential(MakeSecureString(DBInstance), SecureStoreCredentialType.Generic));
break;
case SecureStoreCredentialType.Key:
break;
case SecureStoreCredentialType.Password:
creds.Add(new SecureStoreCredential(MakeSecureString(userPassword), SecureStoreCredentialType.Password));
break;
case SecureStoreCredentialType.Pin:
break;
case SecureStoreCredentialType.UserName:
creds.Add(new SecureStoreCredential(MakeSecureString(userName), SecureStoreCredentialType.UserName));
break;
case SecureStoreCredentialType.WindowsPassword:
break;
case SecureStoreCredentialType.WindowsUserName:
break;
default:
break;
}
}
iss.SetCredentials(targetApplicationID, credentials);
iss.SetUserCredentials(targetApplicationID, ssClaim, credentials);
}
}
}
public void CreateTargetApplication(string targetApplicationID, string targetApplicationContactEmail)
{
var iss = GetISecureStore();
var apps = iss.GetApplications();
var result = apps.Where(a => a.ApplicationId == targetApplicationID);
if (result.Count() == 0)
{
var ta = new TargetApplication(
targetApplicationID,
targetApplicationID,
targetApplicationContactEmail,
20,
TargetApplicationType.Individual,
null
);
var taf1 = new TargetApplicationField("UserName", false, SecureStoreCredentialType.UserName);
var taf2 = new TargetApplicationField("Password", true, SecureStoreCredentialType.Password);
var taf3 = new TargetApplicationField("DBInstance", false, SecureStoreCredentialType.Generic);
var oSecureStoreServiceClaimList = new List<SecureStoreServiceClaim>();
var claim = SPClaimProviderManager.CreateUserClaim(SYSTEMACCOUNT, SPOriginalIssuerType.Windows);
var adminClaim = new SecureStoreServiceClaim(claim);
oSecureStoreServiceClaimList.Add(adminClaim);
var claimcurrent = SPClaimProviderManager.CreateUserClaim(WindowsIdentity.GetCurrent().Name, SPOriginalIssuerType.Windows);
var ssClaimCurrent = new SecureStoreServiceClaim(claimcurrent);
oSecureStoreServiceClaimList.Add(ssClaimCurrent);
var targetClaims = new TargetApplicationClaims(oSecureStoreServiceClaimList, null, null);
iss.CreateApplication(ta, new List<TargetApplicationField>() { taf1, taf2, taf3 }, targetClaims);
}
}
public void DeleteTargetApplication(string targetApplicationID)
{
var iss = GetISecureStore();
var apps = iss.GetApplications();
var result = apps.Where(a => a.ApplicationId == targetApplicationID);
if (result.Count() > 0)
{
iss.DeleteApplication(targetApplicationID);
}
}
#region private method
private static string ToClrString(System.Security.SecureString secureString)
{
var ptr = Marshal.SecureStringToBSTR(secureString);
try
{
return Marshal.PtrToStringBSTR(ptr);
}
finally
{
Marshal.FreeBSTR(ptr);
}
}
private static SecureString MakeSecureString(string value)
{
if (value == null)
{
return null;
}
var secureContent = new SecureString();
var chArray = value.ToCharArray();
for (int i = 0; i < chArray.Length; i++)
{
secureContent.AppendChar(chArray[i]);
chArray[i] = '0';
}
return secureContent;
}
private ISecureStore GetISecureStore()
{
var context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
var ssp = new SecureStoreServiceProxy();
var iss = ssp.GetSecureStore(context);
return iss;
}
private static SPSite GetCentralAdminSite()
{
var adminWebApp = SPAdministrationWebApplication.Local;
SPSite adminSite = null;
if (adminWebApp != null)
{
var adminSiteUri = adminWebApp.GetResponseUri(SPUrlZone.Default);
if (adminSiteUri != null)
{
adminSite = adminWebApp.Sites[adminSiteUri.AbsoluteUri];
}
}
return adminSite;
}
#endregion
}
}
Reference :
Code Snippet: Get User Credentials Using the Default Secure Store Provider