Condividi tramite


RDP and CredMan

One common question asked by our customer is how to programmatically store credentials for connecting to both a Remote Desktop Gateway and Remote Desktop Servers?

End Users will notice that the credentials to access these servers are available in the Credential Manager Application via the Control Panel.

Programmatically, an application can write credentials to the Credential Manager via the Credential Manager (CredMan) APIs.

The way the Credential Manager works is that credentials are associated with a "Target Name".

The information you would need to store is the following for a remote desktop gateway server where GATEWAYSERVER is the name of the Remote Desktop Gateway Server. RDSERVER is the name of the Remote Desktop Server.

//
// RD Gateway Server: SERVER
// USER: DOMAIN\USER
// PASSWORD: PASSWORD
//

Here is some example code:

PCREDENTIAL_TARGET_INFORMATION pcti;

CredGetTargetInfo(L"GATEWAYSERVER", 0, &pcti))

CREDENTIAL cred;
TCHAR *password = _T("GATEWAYPASSWORD");

ZeroMemory( &cred, sizeof(CREDENTIAL) );
cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
cred.Flags = 0;
cred.Type = CRED_TYPE_DOMAIN_PASSWORD;
cred.TargetName = _T("GATEWAYSERVER");
cred.UserName = _T("DOMAIN\\administrator");
cred.CredentialBlob = (BYTE *) password;
cred.CredentialBlobSize = ( lstrlen( password ) + 1 ) * sizeof(TCHAR);

CredWriteDomainCredentials(pcti, &cred, 0);
CredFree((PVOID)pcti);

//
// RD Server
//

ZeroMemory( &cred, sizeof(CREDENTIAL) );
cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
cred.Flags = 0;
cred.Type = CRED_TYPE_DOMAIN_PASSWORD;
cred.TargetName = _T("TERMSRV/RDSERVER");
cred.UserName = _T("DOMAIN\\administrator");
cred.CredentialBlob = (BYTE *) password;
cred.CredentialBlobSize = ( lstrlen( password ) + 1 ) * sizeof(TCHAR);

CredWrite(&cred, 0);

For references to CredWrite on MSDN, see the following:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa375187(v=vs.85).aspx

and for CredWriteDomainCredentials:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa375189(v=vs.85).aspx

Let me know if you have any questions and follow us on Twitter, www.twitter.com/WindowsSDK