saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.09k stars 107 forks source link

Feature | Add header authenticator class #321

Closed markwalet closed 12 months ago

markwalet commented 1 year ago

I have to consume some weird API's in one of my projects at work. That's why I figured a more general header authenticator class could be of good use. I'm using this one as a custom authenticator in my project right now but I wanted to share it in the case someone else could use it as well.

I couldn't find any dedicated authenticator tests, so I only added the helper method in the AuthenticatesRequests trait to keep it consistent with the rest. If I'm missing anything, please let me know. Feel free to close the MR if this kind of authenticator is not desirable in Saloon.

markwalet commented 1 year ago

I tried to reuse this class in other authenticators as well. But I found that it didn't really help with readability:

class TokenAuthenticator extends HeaderAuthenticator implements Authenticator
{

    public function __construct(
        public string $token,
        public string $prefix = 'Bearer'
    ) {
        parent::__construct(
            trim($this->prefix . ' ' . $this->token),
        );
    }
}
Sammyjo20 commented 1 year ago

Hey @markwalet thank you, this looks like a nice PR!

I was wondering, is this similar to the TokenHeader already provided? I wonder if we could customise that authenticator to have a third $header = 'Authorization' instead maybe?

markwalet commented 1 year ago

I mean that's fine by me as well, but if the prefix becomes optional, there's an extra if-statement in that class to remove the extra whitespace when needed. I'm fine with that but you have the chance that it obfuscates the main use-case for the class. Separating them out into multiple classes makes more sense to me personally. Just to give the end-user some more explicit cases to choose from.

But I'm not the maintainer, either way is fine for me. Just let me know what your preference is :)