In my previous post I explained how to add HTTP Basic authentication to a DD4T REST Service.
If you have done that and your application is consuming content from the REST service, your request should end up in HTTP 403 Not Authorized. This is to be expected, because you have now implemented authentication on the REST service, but the client – the DD4T Rest Provider – does not add any authentication headers to the request by default.
Fortunately, the provider is designed in such a way that the implementer can add any Authentication header to the request before it is sent. This is not limited to authentication headers, the whole request pipeline can be adjusted, using a so-called DelegatingHandler.
To find out more about pipelines and DelegatingHandlers, which were introduced with the ASP.NET Web Api, see http://www.asp.net/web-api/overview/advanced/http-message-handlers.
For each request, there is a HttpClient created by HTTPClientFactory.Create(DelegatingHandler[] handlers), the client will execute all the delegatingmessage classes before the actual request. Within the DD4T.Provider.Rest there is a “DefaultHttpMessageHandlerFactory” available, which implements “IHttpMessageHandlerFactory”.
The “DefaultHttpMessageHandlerFactory” is registered by the various DD4T DI Containers as a default. However, this default does not add any authentication headers. We need to override this class and implement the authentication logic ourselves.
DD4T allows the implementer to override the DefaultHttpMessageHandlerFactory and add authentication to the request pipeline.
See here
So far we have crated a class (HttpClientAuthentication) that adds HTTP Basic Authentication headers to the request. Now all we need to do is to override the DefaultHttpMessageHandlerFactory with HttpClientAuthentication. this can be done by Registering the class into a DI container before the standard call to DD4T. The code snippet below demonstrates that, using the Autofac DI container.
All the request created by the DD4T.Providers.Rest will add HTTP Basic Authentication to the request header.