maven-publish repository credentials depend on custom task

I have a custom task to get credentials from a server:

task getToken {
    ext.token = // curl whatever
}

I would like to use the output of this task in the credentials block in the publications repositories, something like this:

publishing {
    publications {
        myPublication(MavenPublication) {
            from components.java
        }
    }

    repositories {
        maven {
            url = "https://somewhere.com/repo"

            credentials {
                username System.properties['user.name']
                password getToken.token
            }
        }
    }
}

However, I don’t know when the credentials there are resolved, and obviously the task getToken would need to have completed before-hand.

How do I achieve this?