System Center SMA Authorization Error

Error

This week I wrote a runbook that started other runbooks as separate processes with Start-SMARunbook. In the lab the runbook worked as it should, but in production I received an Authentication error, something like 401 Unauthorized.
It worked if you use Basic Authentication (with -AuthenticationType Basic) but I wanted to use Windows Authentication. I use Service Management Automation 2016, but this also happens on 2012R2.

Setup

The setup in the lab is very simple: one web service and one worker.
In the production there are 2 SMA web services and runbook workers with a load balancer in front.

Everything was set up according to the SMA whitepaper.

Solution

There are two parts involved in the solution. You have to set SPNs and change the IIS configuration. This solved the error in my case.

Service Principle Name

You have to set SPN's for the service account under which the application pool of the SMA web service runs.
In
svc-scsmaweb is the service account
smaweb1 and smaweb2 are the servers with the webservice
sma is the virtual name of the SMA web service

SetSPN.exe -A HTTP/smaweb1 contoso\svc-scsmaweb  
SetSPN.exe -A HTTP/smaweb1.contoso.com contosos\svc-scsmaweb  
SetSPN.exe -A HTTP/smaweb2 contoso\svc-scsmaweb  
SetSPN.exe -A HTTP/smaweb2.contoso.com contoso\svc-scsmaweb  
SetSPN.exe -A HTTP/sma contoso\svc-scsmaweb  
SetSPN.exe -A HTTP/sma.contoso.com contoso\svc-scsmaweb  
IIS Configuration

You have to change the configuration file ApplicationHost.config which you can find under %windir%\system32\inetsrv\config\ on every server running the web service. Somewhere at the end of the file you can find the application pool settings, location path refers to your application pool.

...
<location path="SMA">  
        <system.webServer>
            <security>
                <authentication>
                    <windowsAuthentication enabled="true" useKernelMode="true">
...

Now add useAppPoolCredentials="true" to this setting:

                    <windowsAuthentication enabled="true" useKernelMode="true" useAppPoolCredentials="true">

This setting configures IIS to use the service account for the authentication instead of the machine account in the kernel mode.
Don't forget you have to add this on every server running the web service.