Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Odata Client - How to add oAuth Token in each request header?

In Microsoft oData v4 proxy client, there is an option to add auth token into each request. It can be achieved by following way:

var container = new Default.Container(new Uri(http://localhost:9000/));

//Registering the handle to the BuildingRequest event. 
container.BuildingRequest += (sender, e) => OnBuildingRequest(sender, e, accessToken);


//Every time a OData request is build it adds an Authorization Header with the acesstoken 
private static void OnBuildingRequest(object sender, BuildingRequestEventArgs e, TokenResponse token)
{
 e.Headers.Add("Authorization", "Bearer " + token.AccessToken);
}

How can I do the same using simple odata client?

like image 918
Rahul Avatar asked Nov 28 '22 13:11

Rahul


2 Answers

Apparently I should provide an explanation of why this is the answer.

Explanation: this is how you add the token for Simple ODataClient.

var settings = new ODataClientSettings(new Uri("http://localhost:9000/"));
settings.BeforeRequest += delegate(HttpRequestMessage message)
{
    message.Headers.Add("Authorization", "Bearer " + token.AccessToken);
};

var client = new ODataClient(settings);
like image 199
Paul - Soura Tech LLC Avatar answered Dec 28 '22 10:12

Paul - Soura Tech LLC


Instead of using the delegate method to intercept and add the Authorization header on every Http call, a clearer/cleaner solution is to instantiate the ODataClient with an HttpClient instance.

This also allows you to control the HttpClient lifecycle and re-use it ( as you should be doing normally anyway! ) otherwise ODataClient will create a new HttpClient instance on every call and that is just inefficient and causes lots of churn on the socket layer. Not normally a problem but can be on high volume code so just a good habit.

The code below is an extract of a .Net core app using an Azure AD OAuth2 token to connect to a Dynamics 365 OData Web API.

        httpClient.BaseAddress = new Uri(yourODataServiceRootURL);
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", yourBearerAccessToken);

        //Use the httpClient we setup with the Bearer token header
        var odataSettings = new ODataClientSettings(httpClient, new Uri("api/data/v9.1", UriKind.Relative));

        var odataClient = new ODataClient(odataSettings);
like image 45
Rohan Avatar answered Dec 28 '22 11:12

Rohan