如何将OAuth2.0与OData客户端代码生成器集成?

时间:2015-01-06 12:18:39

标签: c# visual-studio oauth odata asp.net-web-api

我开发了一个实现OAuth2.0和OData的WebApi。

现在我正在建立一个客户端来测试到目前为止我已经实现了什么。我使用OData客户端代码生成器为OData生成了模板,但是如何在OData请求中引入de访问令牌?

知道如何扩展OData模板以引入OAuth2.0方案吗? 或者更简单的方法是,如何在每个OData请求中引入OAuth访问令牌?

更新

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

2 个答案:

答案 0 :(得分:16)

经过一番研究后,我找到了解决方案:

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

答案 1 :(得分:5)

如果您想将访问令牌添加为HTTP请求标头,以下示例应该有所帮助:

var context = new DefaultContainer(new Uri("http://host/service/"));
context.SendingRequest2 += (s, e) => e.RequestMessage.SetHeader("headerName", "headerValue");

在您指定此代码后发送的每个请求都将包含此标头。