10

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?

UPDATE

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);
     }
}
João Antunes
  • 798
  • 8
  • 27

2 Answers2

16

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);
  }
João Antunes
  • 798
  • 8
  • 27
5

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.

Yi Ding - MSFT
  • 2,864
  • 16
  • 16
  • I thank you for the help Yi Ding, I've found a similiar solution. Instead of adding the header before sending the request, I had add the authentication header when the request is build. – João Antunes Jan 08 '15 at 10:26
  • @JoãoAntunes You are right. The `BuildingRequest` event handlers also work. – Yi Ding - MSFT Jan 09 '15 at 01:30