Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate OAuth2.0 with OData Client Code Generator?

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);
     }
}
like image 986
João Antunes Avatar asked Jan 06 '15 12:01

João Antunes


People also ask

What are the authentication options for API clients accessing the OData API?

The OData API is protected by means of Basic Auth and OAuth.

What is client application in OAuth2?

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.


2 Answers

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);
  }
like image 57
João Antunes Avatar answered Oct 06 '22 18:10

João Antunes


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.

like image 36
Yi Ding - MSFT Avatar answered Oct 06 '22 19:10

Yi Ding - MSFT