Passing dynamic authentication credentials to powerGateServer

How to pass different credentials to powerGateServer on each client

Description

If your webservice uses basic authentication and you want every user to login with their own credentials you need to pass those credentials to powerGateServer and then grab them in your plugin's CRUD methods.

In order to pass the credentials to powerGateServer you can use the html headers. The below sample code uses fix values for demonstration purposes, as this article is mainly about how to pass them to powerGateServer.

Connect-ERP -Service "http://myServer:8080/coolOrange/ErpServices" -OnConnect {
    param($settings)

    $settings.BeforeRequest = [Action[System.Net.Http.HttpRequestMessage]] {
            param($request)
 
            $username = "username"
            $password = "secret"
            $authorization = "Basic " + [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($username + ":" + $password));
            $request.Headers.Add("Authorization", $authorization)
    }
}

In your powerGateServer plugin you have to add a reference to System.ServiceModel.Web. Afterwards you can use System.ServiceModel.Web.WebOperationContext in your CRUD methods to access the html header and use the ecoded string to authenticate with your webservice.

The below example grabs the Authorization header that was set in Connect-ERP

public override IEnumerable<Material> Query(IExpression<Material> expression)
{
    if (System.ServiceModel.Web.WebOperationContext.Current != null)
    {
        if (System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("Authorization"))
        {
            var authorization = System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers.Get("Authorization");
        }
    }
//...