How to add Bearer token to Simple OData Client

3.1k Views Asked by At

New to OData, I need to access SAP Odata Web Service that required Authentication and Token. Say I have the token hardcoded. How to add this token to Simple OData Client?

var settings = new Simple.OData.Client.ODataClientSettings();

settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");

settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);

Please kindly help me.

Update --

In this link : Simple Odata Client - How to add oAuth Token in each request header?

It didnot show how to add the hardcoded Token. For my problem, I need to add a given token and make a Odata Request. I check the Odata.org website, I dont seems to find any example for my case.

I have no experience on simple.Odata.client, Can some1 be kind enough to show me how.

Thanks

2

There are 2 best solutions below

0
On

I believe you can use the ODataClientSettings.BeforeRequest action to alter the request before it is sent.

In the example below I set the Authorization header of the request to 'Bearer <Token>':

settings.BeforeRequest = req => {
    req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Your_Token_Here");
};

Of course it is up to you to configure the request for you specific type of authentication.

0
On

The URL you use in your example is clearly wrong and not the OData URL for SAP.

You need the base URL for the "yourODataServiceRootURL" below and then add the relative path later in the ODataclient setting eg. "api/data/v9.1"

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 externally.

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);