Don't try to get authentication working just via the API - its way too hard.
Use the ZAP desktop to set up authentication - that way you can see exactly whats happening.
Once you've got it working then export the context and any other configuration (like script), import those into your test environment and retest there.
Cheers,
Simon