I've developed a WebApi that implements OAuth2.0 and OData.
Now I'm making a client to test what I've implemented so far. I've generated the templates for OData using the OData Client Code Generator, but how can I introduce de access token in the OData request?
Any idea how to extend the OData templates to introduce the OAuth2.0 scheme? Or a more simpler way, how do I introduce OAuth access token in every OData request?
static void Main(string[] args)
{
var container = new Default.Container(new Uri(baseurl));
TokenResponse accessToken = null;
try
{
accessToken = GetToken();
}
catch (Exception ex)
{
Console.WriteLine("Can't do nothing without an access token...");
return;
}
//I want to introduce in every request the following information:
//Basic autentication header with cliendId + clientSecret
//Access token
//How do I introduce them before making the call on the OData service?
foreach (var s in container.ServiceSessions)
{
string format = ";
Console.WriteLine("PKID:{0}", s.PKID);
}
}
The OData API is protected by means of Basic Auth and OAuth.
Each OAuth 2.0 provider can have multiple client application credentials. Each set of credentials represents an application that has been registered with the provider. Upon registering, the application is assigned a client ID and secret and can designate a redirect URL for receiving access codes.
After a bit of research I've found the solution:
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);
}
If you'd like to add the access token as a HTTP request header, the following sample should help:
var context = new DefaultContainer(new Uri("http://host/service/"));
context.SendingRequest2 += (s, e) => e.RequestMessage.SetHeader("headerName", "headerValue");
Every request sent after you've specified this code will include this header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With