首页 > 编程语言 >D365: Graph API(三)程序调用Graph API

D365: Graph API(三)程序调用Graph API

时间:2022-12-26 16:45:52浏览次数:44  
标签:Graph request System D365 userList token API str public

D365: Graph API(三)程序调用Graph API

在D365中,系统通过GraphAPIClient封装了Graph API接口,可以直接通过调用SysUserMSODSImportHelper::getGraphAPIClient().ListUsers().GetEnumerator()来获取AAD的用户列表,但是通过此方式,有一些限制条件,不能获取到所有字段信息,不能自定义筛选和不能指定字段进行查询。

在D365中,创建用户需要手工进行添加或者手工来导入,当如果有客户希望系统可以自动根据一定规则从AAD检索用户信息直接导入到D365来创建用户,如果通过GraphAPIClient来做,由于上面的一些限制条件,导致有些需求我们无法实现,例如有些字段GraphAPIClient是获取不到的,像office location, onPremisesSamAccountName, employeeid等等,还比如,如果需要做一些筛选,某些特定用户不需要导入到D365,GraphAPIClient不能指定筛选条件

出于上面的限制条件,要实现用户创建自动化,我们需要借助于Graph API,通过代码进行直接调用。

实现跟前面讲到的Postman一样,先获取token,在根据token请求API,下面是具体的逻辑实现

//生成token
public static str getGraphToken(str _tenantId, str _clientId, str _clientSecret) { System.Net.HttpWebRequest request; System.Net.HttpWebResponse response; System.Text.ASCIIEncoding encodingASCII; System.Net.WebHeaderCollection httpHeader; VyaAuthorizationToken authorizationToken = new VyaAuthorizationToken(); System.IO.Stream requestStream, receiveStream; System.IO.StreamReader readStream; CLRObject clrObj; str postData; str graphUrl = strFmt("https://login.microsoftonline.com/%1/oauth2/v2.0/token", _tenantId); ; new InteropPermission(InteropKind::ClrInterop).assert(); httpHeader = new System.Net.WebHeaderCollection(); clrObj = System.Net.WebRequest::Create(graphUrl); request = clrObj; request.set_Method("POST"); request.set_KeepAlive(true); request.set_ContentType("application/x-www-form-urlencoded"); postData = "client_id=" + _clientId; postData += "&scope=https://graph.microsoft.com/.default"; postData += "&client_secret=" + _clientSecret; postData += "&grant_type=client_credentials"; encodingASCII = new System.Text.ASCIIEncoding(); var data = encodingASCII.GetBytes(postData); request.ContentLength = data.Length; requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); response = request.GetResponse(); receiveStream = response.GetResponseStream(); readStream = new System.IO.StreamReader(receiveStream, System.Text.Encoding::get_UTF8()); str result = readStream.ReadToEnd(); authorizationToken = FormJsonSerializer::deserializeObject(classNum(VyaAuthorizationToken), result); response.Close(); readStream.Close(); return authorizationToken.access_Token; }
//序列化返回token的json
[DataContractAttribute] class VyaAuthorizationToken { public str token_Type; public str resource; public str access_Token; public real expires_In; public real not_Before; public real expires_On; [DataMemberAttribute('token_type')] public str paramToken_type(str _token_type = token_type) { token_type = _token_type; return token_type; } [DataMemberAttribute('resource')] public str paramResource(str _resource = resource) { resource = _resource; return resource; } [DataMemberAttribute('access_Token')] public str paramAccess_Token(str _access_Token = access_Token) { access_Token = _access_Token; return access_Token; } [DataMemberAttribute('expires_In')] public real paramExpires_In(real _expires_In = expires_In) { expires_In = _expires_In; return expires_In; } [DataMemberAttribute('not_Before')] public real paramNot_Before(real _not_Before = not_Before) { not_Before = _not_Before; return not_Before; } [DataMemberAttribute('expires_On')] public real paramExpires_On(real _expires_On = expires_On) { expires_On = _expires_On; return expires_On; } }
//根据请求地址和token,获取到用户信息Json
public static str getUserProperty(str _graphUrl,
                                      str _token)
    {
        System.Net.HttpWebRequest       request;
        System.Net.HttpWebResponse      response;
        System.Exception                ex;
        System.Net.WebHeaderCollection  httpHeader;
        System.IO.Stream                requestStream, responseStream;
        System.IO.StreamReader          streamRead;
        System.IO.StreamWriter          streamWriter;
        CLRObject                       clrObj;
        str                             returnJson;
        container                       dataList;
        Map                             mapData;
        ;
        try
        {
            httpHeader = new System.Net.WebHeaderCollection();
            new InteropPermission(InteropKind::ClrInterop).assert();
            clrObj = System.Net.WebRequest::Create(_graphUrl);
            request = clrObj;

            // adding headers
            httpHeader.Add("ConsistencyLevel", "eventual");
            httpHeader.Add("Authorization", strFmt("Bearer %1", _token));
            request.set_Method("GET");
            request.set_KeepAlive(true);
            request.set_ContentType("application/json");
            request.set_Headers(httpHeader);

            response   = request.GetResponse();
            streamRead = new System.IO.StreamReader(response.GetResponseStream());
            returnJson = streamRead.ReadToEnd();
        }
        catch
        {
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }

        return returnJson;

    }
//返回的用户信息进行json解析,并存储在container中
public container userList()
    {
        Map                 userPropertyJsonMap, userPropertyMap;
        MapEnumerator       userPropertyMapEnum;
        container           userList, userListAll;
        str                 userPropertyJson;
        str                 employeeIdAAD;
        str                 userPrincipalNameAAD;
        str                 nextLinkAAD;
        str                 token;
        SystemParameters    systemParameters = SystemParameters::find();
        UserInfo            userInfo;
        int                 rows = 1;
        ;
        str graphUrl        = systemParameters.VyaGraphURL;
        str tenant_id       = systemParameters.VyaGraphTenantId;
        str clientId          = systemParameters.VyaGraphClientId;
        str clientSecret    = systemParameters.VyaGraphSecret;
        token                 = VyaUserAutoGenerateFromAAD::getGraphToken(tenant_id, clientId, clientSecret);
        userPropertyJson    = VyaUserAutoGenerateFromAAD::getUserProperty(graphUrl, token);
        userPropertyJsonMap = RetailCommonWebAPI::getMapFromJsonString(userPropertyJson);
        
        if (userPropertyJsonMap.exists(#Value))
        {
            userList    = userPropertyJsonMap.lookup(#Value);
            userList    = conDel(userList, 1, 3);
        }
        if (userList)
        {
            userListAll    = conIns(userListAll, 1, userList);
        }
        if (userPropertyJsonMap.exists(#NextLink))
        {
            nextLinkAAD = userPropertyJsonMap.lookup(#NextLink);
            while (nextLinkAAD != "")
            {
                [userList, nextLinkAAD]    = this.getNextUserList(nextLinkAAD, token);
                if (userList)
                {
                    rows++;
                    userListAll    = conIns(userListAll, rows, userList);
                }
            }
        }
        
        return userListAll;
    }

    public container getNextUserList(str _nextLink, str _token)
    {
        System.Net.HttpWebRequest       request;
        System.Net.HttpWebResponse      response;
        str                             nextLink, returnJson;
        container                       userList;
        Map                             userMap;
        CLRObject                       clrObj;
        System.Exception                ex;
        System.Net.WebHeaderCollection  httpHeader;
        System.IO.Stream                requestStream, responseStream;
        System.IO.StreamWriter          streamWriter;
        ;
        try
        {
            httpHeader  = new System.Net.WebHeaderCollection();
            new InteropPermission(InteropKind::ClrInterop).assert();
            clrObj      = System.Net.WebRequest::Create(_nextLink);
            request     = clrObj;
            httpHeader.Add("ConsistencyLevel", "eventual");
            httpHeader.Add("Authorization", strFmt("Bearer %1", _token));
            request.set_Method("GET");
            request.set_KeepAlive(true);
            request.set_ContentType("application/json");
            request.set_Headers(httpHeader);

            response    = request.GetResponse();
            System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream());
            returnJson  = streamRead.ReadToEnd();
            userMap     = RetailCommonWebAPI::getMapFromJsonString(returnJson);
            if (userMap.exists(#Value))
            {
                userList    = userMap.lookup(#Value);
                userList    = conDel(userList, 1, 3);
            }
            if (userMap.exists(#NextLink))
            {
                nextLink = userMap.lookup(#NextLink);
            }
        }
        catch
        {
            //exception
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }
        return [userList, nextLink];
    }

 

标签:Graph,request,System,D365,userList,token,API,str,public
From: https://www.cnblogs.com/dingkui/p/17006147.html

相关文章

  • D365: Graph API(二)Postman调用Graph API(国内版)
    D365:GraphAPI(二)Postman调用GraphAPI(国内版)跟国际版的方式一模一样,只是请求和scope的地址做相应的调整获取token地址:https://login.chinacloudapi.cn/{{tenant_id......
  • elasticsearch中SearchApi的详解
     ​搜索流程当一个搜索请求被发送到某个节点时,这个节点就变成了协调节点。 这个节点的任务是广播查询请求到所有相关分片并将它们的响应整合成全局排序后的结果集合,这个结......
  • NPAPI和PPAPI开发
    环境: [1]VisualStudio2010SP1  VisaulStuio 2013Update4 [2]Python2.7 [3]Firefox41.0.1 [4]IE11 [5]Googlechrome45.0.2454.101  [6]Opera32.0 ......
  • ppapi,npapi
    PPAPI也就是PepperPluginAPI,是在原有网景NPAPI(NetscapePluginAPI)基础上发展而来的。NPAPI是当今最流行的插件架构,几乎所有浏览器都支持,不过存在很大的安全隐患,插件可......
  • 虚假新闻检测(GET)《Evidence-aware Fake News Detection with Graph NeuralNetworks》
    论文信息论文标题:Evidence-awareFakeNewsDetectionwithGraphNeuralNetworks论文作者:WeizhiXu,JunfeiWu,QiangLiu,ShuWu,LiangWang论文来源:2022WWW论文......
  • 支付接口的API什么?SDK是什么?
    随着移动支付的发展速度越来越快,各第三方支付和第四方支付成为移动支付的中流砥柱,而面向市场需求,需要不断的提高自己的技术水平,特别是现在商户对于支付安全、支付便捷的需求......
  • Spring Boot中使用Swagger2构建强大的RESTful API文档
    由于SpringBoot能够快速开发、便捷部署等特性,相信有很大一部分SpringBoot的用户会用来构建RESTfulAPI。而我们构建RESTfulAPI的目的通常都是由于多终端的原因,这些终端会......
  • 适合写API接口文档的管理工具有哪些?
    现在越来越流行前后端分离开发,使用ajax交互。所以api接口文档就变的十分有意义了,目前市场有哪些比较优秀的接口文档管理工具呢?1、MinDoc网址:https://www.iminho.me/MinDoc......
  • pg_graphql 1.0 发布了
    pg_graphql是supabse团队使用pgx扩展开发的pggraphql扩展,实际上官方的graphl支持是演变了好几个版本的,学习下官方博客的演变还是很值得的看看如何进行设计参考资料h......
  • 学会使用这10个有用的Web API,让你的开发效率瞬间提升10倍
    英文| https://blog.bitsrc.io/10-useful-web-apis-for-2020-8e43905cbdc5翻译| web前端开发(如WebWorker,Fetch等),但是我个人更喜欢使用其他一些不太流行的API,我建议你也尝......