I am trying to customize Windows Azure Pack using REST API. To authenticate the API, I need the token. I am able run the SampleAuthApplication (Code below), but that is in .NET . I want to implement the same thing in Node.js
Here is the Program.cs
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Net;
using System.Net.Security;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text;
namespace RDFEAPICallsv2
{
class Program
{
static void Main(string[] args)
{
//// Replace these values
string EnvironmentToUse = "https://wap";
string domainName = "anant.ad";
string userName = "anant/administrator";
string password = "pass#word";
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(delegate { return true; });
//// for Admin Authentication
string windowsAuthSiteEndPoint = EnvironmentToUse + ":30072";
string token = GetWindowsAuthToken(windowsAuthSiteEndPoint, domainName, userName, password, true);
//// for Tenant Authentication
string tenantServiceEndpoint = EnvironmentToUse + ":30071";
//string tenantToken = GetAspAuthToken(tenantServiceEndpoint, userName, password);
// Use the tokens obtained above in the Http client to make the calls
//var httpClient = new HttpClient();
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
public static string GetWindowsAuthToken(string windowsAuthSiteEndpoint, string domainName, string userName, string password, bool shouldImpersonate)
{
string token = null;
Impersonation.Impersonate(domainName, userName, password, () => token = GetWindowsToken(windowsAuthSiteEndpoint));
return token;
}
private static string GetWindowsToken(string windowsAuthSiteEndPoint)
{
var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/wstrust/issue/windowstransport"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.Transport);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/AdminSite"),
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));
return jwtString;
}
static string GetAspAuthToken(string authSiteEndPoint, string userName, string password)
{
var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
//This line is only if we're using self-signed certs in the installation
trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
trustChannelFactory.Credentials.SupportInteractive = false;
trustChannelFactory.Credentials.UserName.UserName = userName;
trustChannelFactory.Credentials.UserName.Password = password;
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
TokenType = "urn:ietf:params:oauth:token-type:jwt",
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));
return jwtString;
}
}
}
This is Impersonation.cs
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
namespace RDFEAPICallsv2
{
public static class Impersonation
{
public enum LogonType
{
/// <summary>
/// This logon type is intended for users who will be interactively using the computer, such as a user being logged on
/// by a terminal server, remote shell, or similar process.
/// This logon type has the additional expense of caching logon information for disconnected operations;
/// therefore, it is inappropriate for some client/server applications,
/// such as a mail server.
/// </summary>
LOGON32_LOGON_INTERACTIVE = 2,
/// <summary>
/// This logon type is intended for high performance servers to authenticate plaintext passwords.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_NETWORK = 3,
/// <summary>
/// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
/// their direct intervention. This type is also for higher performance servers that process many plaintext
/// authentication attempts at a time, such as mail or Web servers.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_BATCH = 4,
/// <summary>
/// Indicates a service-type logon. The account provided must have the service privilege enabled.
/// </summary>
LOGON32_LOGON_SERVICE = 5,
/// <summary>
/// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
/// This logon type can generate a unique audit record that shows when the workstation was unlocked.
/// </summary>
LOGON32_LOGON_UNLOCK = 7,
/// <summary>
/// This logon type preserves the name and password in the authentication package, which allows the server to make
/// connections to other network servers while impersonating the client. A server can accept plaintext credentials
/// from a client, call LogonUser, verify that the user can access the system across the network, and still
/// communicate with other servers.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// <summary>
/// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
/// The new logon session has the same local identifier but uses different credentials for other network connections.
/// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
public enum LogonProvider
{
/// <summary>
/// Use the standard logon provider for the system.
/// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
/// is not in UPN format. In this case, the default provider is NTLM.
/// NOTE: Windows 2000/NT: The default security provider is NTLM.
/// </summary>
LOGON32_PROVIDER_DEFAULT = 0,
/// <summary>
/// Win NT 3.5
/// </summary>
LOGON32_PROVIDER_WINNT35 = 1,
/// <summary>
/// Win NT 4.0
/// </summary>
LOGON32_PROVIDER_WINNT40 = 2,
/// <summary>
/// Win NT 5.0
/// </summary>
LOGON32_PROVIDER_WINNT50 = 3
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(
string username,
string domain,
string password,
LogonType logonType,
LogonProvider logonProvider,
out SafeTokenHandle token);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
public static void Impersonate(string domain, string username, string password, Action handler)
{
SafeTokenHandle safeHandle;
var result = LogonUser(
username,
domain == null ? "." : domain,
password,
LogonType.LOGON32_LOGON_NEW_CREDENTIALS,
LogonProvider.LOGON32_PROVIDER_WINNT50,
out safeHandle);
if (!result)
{
int ret = Marshal.GetLastWin32Error();
throw new Win32Exception(ret);
}
using (safeHandle)
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeHandle.DangerousGetHandle()))
{
handler();
}
}
}
}
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
According to your WCF code, seems that this sample used the windows authentication. If you wanna use node.js to achieve to this result, you maybe need to use the passport.js(https://github.com/auth0/passport-windowsauth) implement the windows authentication.
Also, you can use other idp to authentication your application. Please refer to the official document :https://msdn.microsoft.com/en-us/library/dn508295.aspx
Related
Current we are using JWT tokens to authenticate (which works) but I would like to use reference tokens.
Currently our config is like this:
public static class Config
{
/// <summary>
/// Configures identity server
/// </summary>
public static void ConfigureIdentityServer(this IAppBuilder app, CormarConfig config)
{
// Create our options
var identityServerOptions = new IdentityServerOptions
{
SiteName = "Cormar API",
SigningCertificate = LoadCertificate(),
IssuerUri = "https://cormarapi-test.azurewebsites.net",
// Not needed
LoggingOptions = new LoggingOptions
{
EnableHttpLogging = true,
EnableWebApiDiagnostics = true,
EnableKatanaLogging = true,
WebApiDiagnosticsIsVerbose = true
},
// In membory crap just to get going
Factory = new IdentityServerServiceFactory().Configure(config),
// Disable when live
EnableWelcomePage = true
};
// Setup our auth path
app.Map("/identity", idsrvApp =>
{
idsrvApp.UseIdentityServer(identityServerOptions);
});
}
/// <summary>
/// Configures the identity server to use token authentication
/// </summary>
public static void ConfigureIdentityServerTokenAuthentication(this IAppBuilder app, HttpConfiguration config)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://cormarapi-test.azurewebsites.net/identity",
DelayLoadMetadata = true,
ValidationMode = ValidationMode.Local,
RequiredScopes = new[] { "api" },
ClientId = "api",
ClientSecret = "not_my_secret"
});
AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3.Core.Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
}
/// <summary>
/// Loads the certificate
/// </summary>
/// <returns></returns>
private static X509Certificate2 LoadCertificate()
{
var certPath = $"{ AppDomain.CurrentDomain.BaseDirectory }App_Data\\idsrv3test.pfx";
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, "3A1AFB6E1DC5C3F341E63651542C740DA4148866", false);
certStore.Close();
// If we are on azure, get the actual self signed certificate, otherwise return the test one
return certCollection.Count > 0 ? certCollection[0] : new X509Certificate2(certPath, "idsrv3test");
}
/// <summary>
/// Configure the identity service factory with custom services
/// </summary>
/// <returns></returns>
private static IdentityServerServiceFactory Configure(this IdentityServerServiceFactory factory, CormarConfig config)
{
var serviceOptions = new EntityFrameworkServiceOptions { ConnectionString = config.SqlConnectionString };
factory.RegisterOperationalServices(serviceOptions);
factory.RegisterConfigurationServices(serviceOptions);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); // Allow all domains to access authentication
factory.Register(new Registration<DbContext>(dr => dr.ResolveFromAutofacOwinLifetimeScope<DbContext>()));
factory.UserService = new Registration<IUserService>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IUserService>());
factory.ClientStore = new Registration<IClientStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IClientStore>());
factory.ScopeStore = new Registration<IScopeStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IScopeStore>());
return factory;
}
}
As you can see, I have added the ClientId and ClientSecret to IdentityServerBearerTokenAuthenticationOptions.
If I set my client's AccessTokenType to reference and try to get a reference token, it works and I get a response like this:
"access_token": "631783604e9c35e6b401605fe4809075",
"expires_in": 3600,
"token_type": "Bearer"
But if I then try to access an resource on my server, I get a 401 unauthorized error.
If I swap back to a JWT AccessTokenType I can authenticate and then access my resource with no issues.
As a note, I had set the ClientSecret and the ScopeSecret to the same value, so I would expect it to work.
Am I forgetting to do something?
You cannot locally verify a token when using the reference token type. Since it's unstructured data, with no digitally verifiable signature, your API needs to check the token with IdentityServer.
To do this, change your ValidationMode to ValidationMode.ValidationEndpoint or ValidationMode.Both
From the docs:
ValidationMode can be either set to Local (JWTs only), ValidationEndpoint (JWTs and reference tokens using the validation endpoint - and Both for JWTs locally and reference tokens using the validation endpoint (defaults to Both). - https://identityserver.github.io/Documentation/docsv2/consuming/options.html
I need to get the default credentials from the current logged in user and pass them to my Windows service to check the internet connectivity and upload files to Dropbox. I don't want the user to confirm his/her credentials every time. So how is it possible to get the currently active user's proxy settings + username + password?
This is my Code to retrieve the current User
private static string UserName()
{
string userName = null;
ManagementScope ms = new ManagementScope();
ObjectQuery qry = new ObjectQuery("Select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection result = search.Get();
foreach (ManagementObject rec in result)
userName = rec["UserName"] as string;
string[] buffer = userName.Split('\\');
return buffer[1];
}
and this Code is in use for getting the WindowsIdentity:
private static WindowsIdentity GetWindowsIdentity()
{
string userName = UserName();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName) ??
UserPrincipal.FindByIdentity(UserPrincipal.Current.Context, IdentityType.UserPrincipalName, userName))
{
return user == null
? null
: new WindowsIdentity(user.UserPrincipalName);
}
}
This is what I want to do via service:
System.Diagnostics.Debugger.Launch(); //launch debugger when service runs
WindowsImpersonationContext impersonationContext;
impersonationContext = GetWindowsIdentity().Impersonate();
//try to use the currently logged in user's credentials
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
try
{
WebClient wClient = new WebClient();
string xx = wClient.DownloadString(#"https://dropbox.com");
if (xx == "") //just download the sourcecode to chek if this page is available
return false;
}
catch (Exception ex)
{
using (StreamWriter sw = new StreamWriter(#"C:\Users\Testuser\Desktop\DownloadError.txt", true))
{
sw.WriteLine(ex.ToString());
}
return false;
}
impersonationContext.Undo();
The errorLog always shows, that the service was unable to connect. When i run this from an console or WinForms applications, it works without any problems.
Errorlog:
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.217.17.238:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at BeeShotService.Sender.TrySend(String s) in C:\Users\Testuser\Documents\Visual Studio 2017\Projects\Project_BackupUploder\UploaderService\Sender.cs:Zeile 70.
I've managed to solve the problem for simple webRequests with an additional Class:
class GetProxySettings
{
private const int INTERNET_OPTION_PROXY = 38;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetQueryOption(IntPtr hInternet, uint dwOption, IntPtr lpBuffer, ref int lpdwBufferLength);
/// <summary>
/// Access types supported by InternetOpen function.
/// </summary>
private enum InternetOpenType
{
INTERNET_OPEN_TYPE_PRECONFIG = 0,
INTERNET_OPEN_TYPE_DIRECT = 1,
INTERNET_OPEN_TYPE_PROXY = 3,
}
/// <summary>
/// Contains information that is supplied with the INTERNET_OPTION_PROXY value
/// to get or set proxy information on a handle obtained from a call to
/// the InternetOpen function.
/// </summary>
private struct INTERNET_PROXY_INFO
{
public InternetOpenType DwAccessType
{
get; set;
}
public string LpszProxy
{
get; set;
}
public string LpszProxyBypass
{
get; set;
}
}
internal string[] GetV(WindowsIdentity windowsIdentity)
{
string[] settings = new string[] { "", "" };
using (windowsIdentity.Impersonate())
{
int bufferLength = 0;
IntPtr buffer = IntPtr.Zero;
InternetQueryOption(IntPtr.Zero, INTERNET_OPTION_PROXY, IntPtr.Zero,
ref bufferLength);
try
{
buffer = Marshal.AllocHGlobal(bufferLength);
if (InternetQueryOption(IntPtr.Zero, INTERNET_OPTION_PROXY, buffer,
ref bufferLength))
{
INTERNET_PROXY_INFO proxyInfo = (INTERNET_PROXY_INFO)
// Converting structure to IntPtr.
Marshal.PtrToStructure(buffer, typeof(INTERNET_PROXY_INFO));
// Getting the proxy details.
settings[0] = proxyInfo.LpszProxy.Split(':')[0];
settings[1] = proxyInfo.LpszProxy.Split(':')[1];
}
}
catch { }
}
return settings;
}
}
You need to add the WindowsIdentity of the currently logged-on user and will return a string[] with [0] = proxystring & [1] = proxy port.
The following works well as a service:
WebClient wClient = new WebClient();
wClient.Proxy = new WebProxy( GetProxySettings.GetV(GetWindowsIdentity())[0],GetProxySettings.GetV(GetWindowsIdentity())[1]);
string xx = wClient.DownloadString(#"https://www.dropbox.com");
Is it possible to install a Transport Agent to Exchange Server within a C# programm?
Normally you create your Agent .dll, then you need to open Exchange Management Shell and execute the following commands:
Install-TransportAgent -Name "Agent Name" -TransportAgentFactory "Factory.Class.Name" -AssemblyPath "C:\Path\to\agent.dll"
and
enable-transportagent -Identity "Agent Name"
and setting the priority:
Set-TransportAgent -Identity "Agent Name" -Priority 3
How can I install the transport agent from within a C# application (either calling a PowerShell command or directly using the .NET Framework?
I found a solution using PowerShell directly from C# and calling the corresponding cmdlets:
Note: The full code is available here: https://github.com/Pro/dkim-exchange/blob/master/Src/Configuration.DkimSigner/Exchange/ExchangeServer.cs#L111 and https://github.com/Pro/dkim-exchange/blob/master/Src/Configuration.DkimSigner/Exchange/PowershellHelper.cs#L29
/// <summary>
/// Installs the transport agent by calling the corresponding PowerShell commands (Install-TransportAgent and Enable-TransportAgent).
/// The priority of the agent is set to the highest one.
/// You need to restart the MSExchangeTransport service after install.
///
/// Throws ExchangeHelperException on error.
/// </summary>
public static void installTransportAgent()
{
using (Runspace runspace = RunspaceFactory.CreateRunspace(getPSConnectionInfo()))
{
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
int currPriority = 0;
Collection<PSObject> results;
if (!isAgentInstalled())
{
// Install-TransportAgent -Name "Exchange DkimSigner" -TransportAgentFactory "Exchange.DkimSigner.DkimSigningRoutingAgentFactory" -AssemblyPath "$EXDIR\ExchangeDkimSigner.dll"
powershell.AddCommand("Install-TransportAgent");
powershell.AddParameter("Name", AGENT_NAME);
powershell.AddParameter("TransportAgentFactory", "Exchange.DkimSigner.DkimSigningRoutingAgentFactory");
powershell.AddParameter("AssemblyPath", System.IO.Path.Combine(AGENT_DIR, "ExchangeDkimSigner.dll"));
results = invokePS(powershell, "Error installing Transport Agent");
if (results.Count == 1)
{
currPriority = Int32.Parse(results[0].Properties["Priority"].Value.ToString());
}
powershell.Commands.Clear();
// Enable-TransportAgent -Identity "Exchange DkimSigner"
powershell.AddCommand("Enable-TransportAgent");
powershell.AddParameter("Identity", AGENT_NAME);
invokePS(powershell, "Error enabling Transport Agent");
}
powershell.Commands.Clear();
// Determine current maximum priority
powershell.AddCommand("Get-TransportAgent");
results = invokePS(powershell, "Error getting list of Transport Agents");
int maxPrio = 0;
foreach (PSObject result in results)
{
if (!result.Properties["Identity"].Value.ToString().Equals(AGENT_NAME)){
maxPrio = Math.Max(maxPrio, Int32.Parse(result.Properties["Priority"].Value.ToString()));
}
}
powershell.Commands.Clear();
if (currPriority != maxPrio + 1)
{
//Set-TransportAgent -Identity "Exchange DkimSigner" -Priority 3
powershell.AddCommand("Set-TransportAgent");
powershell.AddParameter("Identity", AGENT_NAME);
powershell.AddParameter("Priority", maxPrio + 1);
results = invokePS(powershell, "Error setting priority of Transport Agent");
}
}
}
}
/// <summary>
/// Checks if the last powerShell command failed with errors.
/// If yes, this method will throw an ExchangeHelperException to notify the callee.
/// </summary>
/// <param name="powerShell">PowerShell to check for errors</param>
/// <param name="errorPrependMessage">String prepended to the exception message</param>
private static Collection<PSObject> invokePS(PowerShell powerShell, string errorPrependMessage)
{
Collection<PSObject> results = null;
try
{
results = powerShell.Invoke();
}
catch (System.Management.Automation.RemoteException e)
{
if (errorPrependMessage.Length > 0)
throw new ExchangeHelperException("Error getting list of Transport Agents:\n" + e.Message, e);
else
throw e;
}
if (powerShell.Streams.Error.Count > 0)
{
string errors = errorPrependMessage;
if (errorPrependMessage.Length > 0 && !errorPrependMessage.EndsWith(":"))
errors += ":";
foreach (ErrorRecord error in powerShell.Streams.Error)
{
if (errors.Length > 0)
errors += "\n";
errors += error.ToString();
}
throw new ExchangeHelperException(errors);
}
return results;
}
Yes, Its possible to install\uninstall Exchange Transport agent using C#. In fact, i have done it.
What i did is, I called exchange cmdlets using PowerShell, and installed the agent on exchange hub server. I also had to stop\start MS Exchange Transport Agent service using C#. Besides, i also had to create the folder, where i had to place agent files, and also grant Network Service read\write permission on that folder.
Regards,
Laeeq Qazi
I have written a class which allows you to run exchange commands either locally or through a remote shell.
The following commands are available in this class:
GetAgentInfo : Receive the transport agent information by passing the NAme as parameter
InstallAgent : Install a transport agent by passing Name, FactoryNAme and Assembly path
EnableAgent : Enable a transport agent
UninstallAgent : Uninstall a transportagent
RestartTransportService : Restart the Microsoft Transport Service
It also verifies what version of Exchange is installed to load the correct SnapIn
Here is the code writte in C#:
/// <summary>
/// This class is used to connect to either an remote or the local exchange powershell and allows you to execute several exchange cmdlets easiely
/// </summary>
public class ExchangeShell : IDisposable
{
/// <summary>
/// registry key to verify the installed exchange version, see <see cref="verifyExchangeVersion"/> method for more info
/// </summary>
private string EXCHANGE_KEY = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{4934D1EA-BE46-48B1-8847-F1AF20E892C1}";
private ExchangeVersionEnum m_ExchangeVersion;
/// <summary>
/// getter to receive the current exchange version (local host only)
/// </summary>
public ExchangeVersionEnum ExchangeVersion { get { return m_ExchangeVersion; } }
public enum ExchangeVersionEnum {
Unknown = 0,
v2010 = 1,
v2013 = 2,
}
public string Host { get; private set; }
/// <summary>
/// stores the powershell runspaces for either local or any other remote connection
/// </summary>
private Dictionary<string, Runspace> m_runspaces = new Dictionary<string, Runspace>();
/// <summary>
/// get the current runspace being used for the cmdlets - only for internal purposes
/// </summary>
private Runspace currentRunspace {
get
{
if (m_runspaces.ContainsKey(this.Host))
return m_runspaces[this.Host];
else
throw new Exception("No Runspace found for host '" + this.Host + "'. Use SetRemoteHost first");
}
}
/// <summary>
/// Call the constructor to either open a local exchange shell or force open the local shell as remote connection (primary used to bypass "Microsoft.Exchange.Net" assembly load failures)
/// </summary>
/// <param name="forceRemoteShell"></param>
public ExchangeShell(bool forceRemoteShell = false)
{
if (!forceRemoteShell)
{
this.m_ExchangeVersion = this.verifyExchangeVersion();
if (this.m_ExchangeVersion == ExchangeVersionEnum.Unknown) throw new Exception("Unable to verify Exchange version");
this.SetLocalHost();
}
else
{
// Use empty hostname to connect to localhost via http://computername.domain/[...]
this.SetRemoteHost("");
}
}
/// <summary>
/// Constructor to open a remote exchange shell
/// TODO: display authentication prompt for different login credentials
/// </summary>
/// <param name="hostName">host of the remote powershell</param>
/// <param name="authenticationPrompt">not yet implemented</param>
public ExchangeShell(string hostName, bool authenticationPrompt = false)
{
// TODO: Implement prompt for authenication different then default
this.SetRemoteHost(hostName);
}
/// <summary>
/// private function to verify the exchange version (local only)
/// </summary>
/// <returns></returns>
private ExchangeVersionEnum verifyExchangeVersion()
{
var hklm = Microsoft.Win32.Registry.LocalMachine;
var exchangeInstall = hklm.OpenSubKey(EXCHANGE_KEY);
if (exchangeInstall != null)
{
var exchangeVersionKey = exchangeInstall.GetValue("DisplayVersion").ToString();
if (exchangeVersionKey.StartsWith("14."))
return ExchangeVersionEnum.v2010;
else if (exchangeVersionKey.StartsWith("15."))
return ExchangeVersionEnum.v2013;
}
return ExchangeVersionEnum.Unknown;
}
/// <summary>
/// set the current runspace to local.
/// Every command will be executed on the local machine
/// </summary>
public void SetLocalHost()
{
if (!this.m_runspaces.ContainsKey("localhost"))
{
RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException psSnapInException = null;
switch (this.m_ExchangeVersion)
{
case ExchangeVersionEnum.v2010:
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out psSnapInException);
break;
case ExchangeVersionEnum.v2013:
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.SnapIn", out psSnapInException);
break;
}
if (psSnapInException != null)
throw psSnapInException;
var runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
this.m_runspaces.Add("localhost", runspace);
}
this.Host = "localhost";
}
/// <summary>
/// Setup a runspace for a remote host
/// After calling this method, currentRunspace is being used to execute the commands
/// </summary>
/// <param name="hostName"></param>
public void SetRemoteHost(string hostName = null)
{
if (String.IsNullOrEmpty(hostName))
hostName = Environment.MachineName + "." + Environment.UserDomainName + ".local";
hostName = hostName.ToLower();
if (!this.m_runspaces.ContainsKey(hostName))
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://" + hostName + "/PowerShell/"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", PSCredential.Empty);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
// THIS CAUSES AN ERROR WHEN USING IT IN INSTALLER
runspace.Open();
this.m_runspaces.Add(hostName, runspace);
}
this.Host = hostName;
}
/// <summary>
/// Get Transport agent info
/// </summary>
/// <param name="Name">name of the transport agent</param>
/// <returns></returns>
public PSObject GetAgentInfo(string Name)
{
PSObject result = null;
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Get-TransportAgent");
ps.AddParameter("Identity", Name);
var res = ps.Invoke();
if (res != null && res.Count > 0)
result = res[0];
}
return result;
}
/// <summary>
/// get a list of exchange server available in the environment
/// </summary>
/// <returns>collection of powershell objects containing of all available exchange server</returns>
public ICollection<PSObject> GetExchangeServer()
{
ICollection<PSObject> result;
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Get-ExchangeServer");
result = ps.Invoke();
}
return result;
}
/// <summary>
/// Install a transport agent
/// </summary>
/// <param name="Name">name of the transportagent</param>
/// <param name="AgentFactory">factory name of the transport agent</param>
/// <param name="AssemblyPath">file path of the transport agent assembly</param>
/// <param name="enable">if true, enable it after successfully installed</param>
/// <returns>if true everything went ok, elsewise false</returns>
public bool InstallAgent(string Name, string AgentFactory, string AssemblyPath, bool enable = false)
{
bool success = false;
if (!System.IO.File.Exists(AssemblyPath))
throw new Exception("Assembly '"+AssemblyPath+"' for TransportAgent '"+ Name +"' not found");
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Install-TransportAgent");
ps.AddParameter("Name", Name);
ps.AddParameter("TransportAgentFactory", AgentFactory);
ps.AddParameter("AssemblyPath", AssemblyPath);
var result = ps.Invoke();
if (result.Count > 0)
{
if (enable)
success = this.EnableAgent(Name);
else
success = true;
}
}
return success;
}
/// <summary>
/// Enable a transport agent
/// </summary>
/// <param name="Name">name of the transport agent</param>
/// <returns>if true everything went ok, elsewise false</returns>
public bool EnableAgent(string Name){
bool success = false;
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Enable-TransportAgent");
ps.AddParameter("Identity", Name);
var result = ps.Invoke();
if (result.Count <= 0) success = true;
}
return success;
}
/// <summary>
/// removes a transport agent
/// </summary>
/// <param name="Name">name of the transport agent</param>
/// <returns>if true everything went ok, elsewise false</returns>
public bool UninstallAgent(string Name)
{
bool success = false;
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Uninstall-TransportAgent");
ps.AddParameter("Identity", Name);
ps.AddParameter("Confirm", false);
var result = ps.Invoke();
if (result.Count <= 0)success = true;
}
return success;
}
/// <summary>
/// restart exchange transport agent service
/// A RESTART OF THIS SERVICE REQUIRED WHEN INSTALLING A NEW AGENT
/// </summary>
/// <returns></returns>
public bool RestartTransportService()
{
bool success = false;
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = this.currentRunspace;
ps.AddCommand("Restart-Service");
ps.AddParameter("Name", "MSExchangeTransport");
var result = ps.Invoke();
if (result.Count <= 0) success = true;
}
return success;
}
public void Dispose()
{
if (this.m_runspaces.Count > 0)
{
foreach (var rs in this.m_runspaces.Values)
{
rs.Close();
}
this.m_runspaces.Clear();
}
}
}
Usage:
// Local
ExchangeShell shell = new ExchangeShell();
var localAgentInfo = shell.GetAgentInfo("YourAgentName");
// continue with a remote call
shell.SetRemoteHost("anotherexchangeserver.your.domain");
var remoteAgentInfo = shell.GetAgentInfo("YourAgentName");
// close all connections
shell.Dispose();
I want to start a Process with Admin rights. When I run the code below the Process complains saying it needs Admin rights:
public class ImpersonationHelper : IDisposable
{
IntPtr m_tokenHandle = new IntPtr(0);
WindowsImpersonationContext m_impersonatedUser;
#region Win32 API Declarations
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2; //This parameter causes LogonUser to create a primary token.
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#endregion
/// <summary>
/// Constructor. Impersonates the requested user. Impersonation lasts until
/// the instance is disposed.
/// </summary>
public ImpersonationHelper(string domain, string user, string password)
{
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(user, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref m_tokenHandle);
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
// Impersonate
m_impersonatedUser = new WindowsIdentity(m_tokenHandle).Impersonate();
}
#region IDisposable Pattern
/// <summary>
/// Revert to original user and cleanup.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Revert to original user identity
if (m_impersonatedUser != null)
m_impersonatedUser.Undo();
}
// Free the tokens.
if (m_tokenHandle != IntPtr.Zero)
CloseHandle(m_tokenHandle);
}
/// <summary>
/// Explicit dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Destructor
/// </summary>
~ImpersonationHelper()
{
Dispose(false);
}
#endregion
}
using (new ImpersonationHelper("xxx.blabla.com", "xxxx", "xxxx"))
{
if (!string.IsNullOrEmpty(txtFilename.Text))
Process.Start(txtFilename.Text);
}
Can you try something like this: Start a new Process as another user
Code sample:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "filename";
proc.StartInfo.Arguments = "args...";
proc.StartInfo.Domain = "domainname";
proc.StartInfo.UserName = "username";
string password = "user entered password";
for (int x = 0; x < password.Length; x++)
{
ssPwd.AppendChar(password[x]);
}
password = "";
proc.StartInfo.Password = ssPwd;
proc.Start();
Correct usage of SecureString and a few extras:
//You should use SecureString like the following
SecureString password = new SecureString();
password.AppendChar('p');
password.AppendChar('a');
password.AppendChar('s');
password.AppendChar('s');
Process process = new Process();
process.StartInfo.UseShellExecute = false;
//Set the working directory if you don't execute something like calc or iisreset but your own exe in which you want to access some files etc..
process.StartInfo.WorkingDirectory = "workingDirectory";
//Full path (e.g. it can be #"C:\Windows\System32\iisreset.exe" OR you can use only file name if the path is included in Environment Variables..)
process.StartInfo.FileName = #"fileName";
process.StartInfo.Domain = "domain";
process.StartInfo.UserName = "userName";
process.StartInfo.Password = password;
process.Start();
EDIT: I don't know why this answer is voted below 0, maybe a little more explanation is needed. If you'll use this in non-interactive environment (like a web application) and you want to run a process with a user, then you have a few options to use the user's password. You can either read password from a storage or from code. A better way; you can store it encrypted. However, if you plan to use it in plain form (maybe temporarily or just to test something etc.), you can use SecureString in a way I described. The accepted answer doesn't use SecureString in a right way. Reading password into a string from console and then putting it into a SecureString is simply WRONG. The accepted answer does NOT secure that string or something but only cheating it. That was the main motivation for me to add this answer. Check link.
Don't forget to add LoadUserProfile=true since without this access denied issues might occur if your application is doing some read write operations
I am following through the RailsCasts episode on PayPal security. I am try to port this code to C# and am using OpenSSL.NET
Also is it possible to do this without using the OpenSSL wrapper library as that uses some unmanaged code?
The ruby code that I am trying to port is this:
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
end
Does anyone know how to do this with C# OpenSSL wrapper?
Turns out I found an article that explains how to do this for C#. So read an follow that tutorial. I used Cygwin Bash Shell to create the keys. I've included the code that I used as it may be helpful :)
This is all code that was published in the book Pro PayPal E-Commerce by Damon Williams
private string EncryptForPayPal()
{
var Server = HttpContext.Current.Server;
string paypalCertPath = Server.MapPath("App_Data/paypal_cert_pem.txt");
string signerPfxPath = Server.MapPath("App_Data/my_pkcs12.p12");
string signerPfxPassword = "your_password_used_when_generating_keys";
string clearText = "cmd=_xclick\n" +
"your_paypal_business_email#somedomain.com\n" +
"currency_code=GBP\n" +
"item_name=Tennis Balls ßü (£12 umlot OK)\n" +
"amount=15.00\n" +
"return=https://localhost:2416/return\n" +
"cancel_return=https://localhost:2416/cancel\n" +
"cert_id=ZSGYTRNCK445J";
FormEncryption ewp = new FormEncryption();
ewp.LoadSignerCredential(signerPfxPath, signerPfxPassword);
ewp.RecipientPublicCertPath = paypalCertPath;
string result = ewp.SignAndEncrypt(clearText);
return result;
}
The FormEncryption class
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using Pkcs = System.Security.Cryptography.Pkcs;
using X509 = System.Security.Cryptography.X509Certificates;
public class FormEncryption
{
private Encoding _encoding = Encoding.Default;
private string _recipientPublicCertPath;
private X509.X509Certificate2 _signerCert;
private X509.X509Certificate2 _recipientCert;
/// <summary>
/// Character encoding, e.g. UTF-8, Windows-1252
/// </summary>
public string Charset
{
get { return _encoding.WebName; }
set
{
if (!string.IsNullOrEmpty(value))
{
_encoding = Encoding.GetEncoding(value);
}
}
}
/// <summary>
/// Path to the recipient's public certificate in PEM format
/// </summary>
public string RecipientPublicCertPath
{
get { return _recipientPublicCertPath; }
set
{
_recipientPublicCertPath = value;
_recipientCert = new X509.X509Certificate2(_recipientPublicCertPath);
}
}
/// <summary>
/// Loads the PKCS12 file which contains the public certificate
/// and private key of the signer
/// </summary>
/// <param name="signerPfxCertPath">
/// File path to the signer's public certificate plus private key
/// in PKCS#12 format</param>
/// <param name="signerPfxCertPassword">
/// Password for signer's private key</param>
public void LoadSignerCredential(string signerPfxCertPath, string signerPfxCertPassword)
{
_signerCert = new X509.X509Certificate2(signerPfxCertPath, signerPfxCertPassword);
}
/// <summary>
/// Sign a message and encrypt it for the recipient.
/// </summary>
/// <param name="clearText">Name value pairs
/// must be separated by \n (vbLf or chr(10)),
/// for example "cmd=_xclick\nbusiness=..."</param>
/// <returns></returns>
public string SignAndEncrypt(string clearText)
{
string result = null;
byte[] messageBytes = _encoding.GetBytes(clearText);
byte[] signedBytes = Sign(messageBytes);
byte[] encryptedBytes = Envelope(signedBytes);
result = Base64Encode(encryptedBytes);
return result;
}
private byte[] Sign(byte[] messageBytes)
{
Pkcs.ContentInfo content = new Pkcs.ContentInfo(messageBytes);
Pkcs.SignedCms signed = new Pkcs.SignedCms(content);
Pkcs.CmsSigner signer = new Pkcs.CmsSigner(_signerCert);
signed.ComputeSignature(signer);
byte[] signedBytes = signed.Encode();
return signedBytes;
}
private byte[] Envelope(byte[] contentBytes)
{
Pkcs.ContentInfo content = new Pkcs.ContentInfo(contentBytes);
Pkcs.EnvelopedCms envMsg = new Pkcs.EnvelopedCms(content);
Pkcs.CmsRecipient recipient = new Pkcs.CmsRecipient(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert);
envMsg.Encrypt(recipient);
byte[] encryptedBytes = envMsg.Encode();
return encryptedBytes;
}
private string Base64Encode(byte[] encoded)
{
const string PKCS7_HEADER = "-----BEGIN PKCS7-----";
const string PKCS7_FOOTER = "-----END PKCS7-----";
string base64 = Convert.ToBase64String(encoded);
StringBuilder formatted = new StringBuilder();
formatted.Append(PKCS7_HEADER);
formatted.Append(base64);
formatted.Append(PKCS7_FOOTER);
return formatted.ToString();
}
}
Then the html form
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr">
<%= Html.Hidden("cmd", "_s-xclick") %>
<%= Html.Hidden("encrypted", cart.PayPalEncypted(returnUrl, instantNotificationurl)) %>
<input type="submit" name="Checkout" value="Checkout" />
</form>