通过 OAuth for REST 通过单个应用程序访问多个服务实例

Jun*_*iro 6 servicenow servicenow-rest-api

我想在 serviceNow(如 Facebook)中创建一个应用程序,它可以通过 OAuth 为不同的实例调用 REST API。

假设,我在 servicenow 的实例 A 中创建了一个应用程序,现在通过适当的 OAuth 和权限机制,我想访问其他实例的 REST API。

到目前为止,我能够创建一个应用程序并将其注册到应用程序注册表中,并且我还能够验证该实例的 Oauth(生成令牌);但现在我想为其他实例执行此操作,而无需每次都创建一个新应用程序。当我尝试这样做时,我收到此错误:

未经授权的客户端:提供的客户端凭据(
您正在使用的服务的凭据)无效或不受信任

Dri*_*man 2

在实例 A 上的应用程序中,您需要保存要连接的每个实例的 OAUTH 凭据。
https://docs.servicenow.com/bundle/paris-servicenow-platform/page/product/meeting-extensibility/task/create-app-registry-meeting-extensibility.html

在您的应用程序中,根据您要连接的实例,您需要为该实例使用正确的凭据。

无法为多个实例重用相同的 OAUTH 令牌,因为可以通过基本身份验证重用相同的用户名:密码组合

但是,您可以为每个连接创建一个 oauth_entity_profile。然后,在执行此操作时,您将请求循环遍历实例列表,然后在发送请求之前注入正确的身份验证。
https://developer.servicenow.com/dev.do#!/reference/api/rome/server/sn_ws-namespace/c_RESTMessageV2API#r_RMV2-setAuthenticationProfile_S_S

同时还使用以下命令调用给定实例的正确网址:
https://developer.servicenow.com/dev.do# !/reference/api/rome/server/sn_ws-namespace/c_RESTMessageV2API#r_RESTMessageV2_setEndpoint_String_endpoint

var instances = [{name: 'instance_x', oauth_id: '2394829384..'}, {name: 'instance_y', oauth_id: '2394829384..'};
for (var i = 0; i < instances.length; i++){
    var inst = instances[i];
    var sm = new sn_ws.RESTMessageV2("<REST_message_record>", "get");  

       //set auth profile to an OAuth 2.0 profile record.
    sm.setAuthenticationProfile('oauth2', inst.oauth_id); 
    sm.setEndpoint("http://web.service.endpoint");


       //In milliseconds. Wait at most 10 seconds for response from http request.
    sm.setHttpTimeout(10000); 
       //Might throw exception if http connection timed out or some issue 
       //with sending request itself because of encryption/decryption of password.
    var response = sm.execute();
    // handle your reponse  
}
Run Code Online (Sandbox Code Playgroud)

其中instances.oauth_id是oauth_entity_profile表中记录的id。需要保持活跃并拥有代币才能发挥作用。