Add User-Agent customization
Reddit's OAuth implementation requires a specific User-Agent header, and it seems they've recently started enforcing this. It would be great to have an easy way to specify this, and perhaps other, custom headers for token requests.
I'm using reqwest in my app and have worked around it like so, but this requires cloning the request to override the headers. Maybe there's a better way to get this behavior without changes to the lib?
That's a requirement I haven't seen before!
Your approach of providing a custom HTTP client to wrap reqwest is exactly what I'd suggest. Is the clone needed though? It seems like you'd just need to add mut to http_client's request argument (which doesn't affect the signature of the function passed to request_async since it's an owned value):
async fn http_client(
mut request: oauth2::HttpRequest,
) -> Result<oauth2::HttpResponse, oauth2::reqwest::Error<reqwest::Error>> {
request.headers.insert(
"User-Agent",
"web:com.kachiclash:v0.5.0 (by /u/dand)".parse().unwrap(),
);
oauth2::reqwest::async_http_client(request).await
}
Does that work?
Otherwise, I probably wouldn't sweat the overhead of this clone since it'll be dwarfed by the cost of the network request anyway.
Ah, you're right that there's no need to clone the request (and I agree that the cost of cloning is likely negligible in any case). I had incorrectly assumed that adding mut to the param makes the function signature incompatible. Thanks for the tip!
I do think it would be nice to have a function like add_extra_header to parallel add_extra_param, but wrapping the http client function is totally workable so please feel free to close this as a wontfix.
You can probably use https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html#method.user_agent which sets the user agent header for all requests using this Client
Edit: Nevermind, I thought it was possible to pass a Client into oauth2 but I must have dreamt that 😅
I'll note that this is also a requirement for Wikimedia sites (including Wikipedia): https://meta.wikimedia.org/wiki/User-Agent_policy
A more convenient way to set the user-agent would be appreciated.
I've just merged 23b952b2, which in 5.0 will allow stateful HTTP clients like a reqwest::Client to passed in instead of a function. This should make it easy to set the User-Agent header once when building the HTTP client, and then it should be applied to each downstream request.
Given (1) that this is easy to implement in user code now, and (2) that these are entirely vendor-created extensions that don't seem to be based on anything in an IETF RFC, I'd prefer not to add anything to the API specifically related to the user agent (which really feels like an attribute of the HTTP client in any case).
That seems like a reasonable solution to this requirement. Thanks!