如何将OAuth2.0与OData客户端代码生成器集成? [英] How to integrate OAuth2.0 with OData Client Code Generator?

查看:81
本文介绍了如何将OAuth2.0与OData客户端代码生成器集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了实现OAuth2.0和OData的WebApi.

I've developed a WebApi that implements OAuth2.0 and OData.

现在,我要让一个客户端来测试到目前为止已实现的功能.我已经使用OData客户端代码生成器为OData生成了模板,但是如何在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?

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

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

推荐答案

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

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

这篇关于如何将OAuth2.0与OData客户端代码生成器集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆