从 SharePoint 在线使用 Secure Azure API

Consume Secure Azure API from SharePoint online

我开发了具有身份验证功能的 Azure API 应用程序,使用 Azure Active Directory 登录,我需要从 SharePoint 在线使用此 API,我
我需要验证并使用 azure API,没有登录提示,每件事都应该在脚本中处理 需要使用 ADAL.js 来验证安全 API ,我找不到关于 JavaScript 代码的任何好的参考,我想知道是否有人有很好的参考 JavaScript 代码应该如何长什么样子?

谢谢!

可以使用 JavaScript 从 SharePoint online 调用受 Azure AD 保护的 Web API,但它非常复杂。

以下步骤供您参考:

  1. 开发受 Azure AD 保护的网络 API
  2. 在同一租户上注册本机应用程序
  3. 为本机应用启用隐式流
  4. 授权本机应用程序从 Azure 门户API访问网络
  5. 使用 admin_consent 为本机应用授予组织权限
  6. 在 web API 项目中为 OAuth 2.0 请求的重定向页面开发网页
  7. 在网页中使用windows.postMessage编写代码将posttoken传给父页面

    $().ready(function () {
        if (window.parent != null) {
            // get the token from URL here
            var token = "123";
            console.log(window.location);
            window.parent.postMessage(token, "*");
        }
    
    })
    
  8. 在 SharePoint 在线页面中,使用 iframe 发送如下代码的隐式流

<iframe id="iframe_id" src="https://login.microsoftonline.com/{tenanit}.onmicrosoft.com/oauth2/authorize?response_type=token&client_id={clientId}&resource={webApiAppIdUri}&redirect_uri={redirect_uri}&prompt=none"></iframe>
<script>
        var token = "";
        window.addEventListener("message", receiveMessage, false);

        function receiveMessage(event) {
            token=event.data;
            console.log(event.data);
        }
      
</script>

这是一个有助于理解进度的图表:

以下是使用 JavaScript 和 ADAL.js 库从 SharePoint 在线调用 azure 托管 API 的步骤,没有签名提示,一切都应该在脚本中使用 ADAL.js 验证安全 API

创建和配置 API

  1. 创造蔚蓝API
  2. 在 azure
  3. 中发布你的 azure API
  4. 浏览到 Azure 门户,select 您的 API 应用程序,select Authentication/Authorizations

    • 设置应用程序服务身份验证:开启

    • 请求我们未通过身份验证时采取的操作:使用 Azure 字典登录

    • 身份验证提供商:Express

  5. 现在 API 受 Azure AD 保护,如果您通过浏览器导航 API,系统将提示您登录

  6. 当我们在快速模式下设置身份验证时,应用程序将自动在 Azure Active 目录中创建,您可以在 Azure AD 应用程序下看到名称
  7. 导航到 Azure 管理门户,单击左侧导航中的 活动目录

  1. 单击将联合到您的 office 365 的目录(或您想要调用 azure API 的任何来源,它使用与您配置的相同 azure 活动目录 API 身份验证)
  2. 单击“应用程序”,您会在列表中找到您的 AD 应用程序,该列表是我们在第 3 步中讨论的使用 Express 方法创建的
  3. 现在我们需要在 AAD 中创建新的应用程序,这将是我们从 office 365 到 Azure 的通信渠道 API,单击页脚上的添加
  4. 输入名称和select“WEB APPLICATION AND/OR WEB AP”选项
  5. 登录 URL 输入您计划从
  6. 调用 Azure API 的在线 SharePoint Url
  7. 对于APP ID URL,输入唯一的Url,这将用作您的应用程序的唯一逻辑标识符。
  8. 应用创建完成后,点击配置,复制Client ID,稍后会用到
  9. 允许其他应用程序下,点击“添加应用程序”,在下一页select“All Apps” 和 select 您在步骤 nr.8 中仔细检查过的 Azure API 应用程序,并确认
  10. 您将被重定向回配置页面,在对其他应用程序的许可下,现在您看到您的 azure API 应用程序已列在此处,单击 授权、select对应用程序的访问
  11. 在页面底部,单击管理清单 > 下载清单t。
  12. 将文件下载到可以编辑的位置。
  13. 在下载的清单文件中,搜索 oauth2AllowImplicitFlow属性。将此 属性 的值从 false 更改为 true,然后保存文件。
  14. 单击管理清单 > 上传清单,然后上传您在上一步中更新的文件。
  15. Azure 管理门户,select 设置并复制相关 AAD 的 AAD 订阅 ID

从 SharePoint Online 调用 Azure API

完成上述步骤后,您可以从 sharePoint online 调用 azure API,它使用与上面相同的 Active 目录

  1. 编辑页面并添加脚本编辑器 Web 部件
  2. 添加以下脚本 · subscriptionId,见第 20 步 · clientId 参见步骤 nr.13

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal.min.js"></script>
<script type="text/javascript">
function CallAzureAPI() {
    "use strict";
  
    var subscriptionId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    var clientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 
    window.config = {
        subscriptionId: subscriptionId,                 
        clientId: clientId,     
        postLogoutRedirectUri: window.location.origin,
        endpoints: {
            AzureApiUri: 'https://xxxxxxxxxxxx.azurewebsites.net'
        }, 
         cacheLocation: 'localStorage' 
    };
    var authContext = new AuthenticationContext(config);    
    var isCallback = authContext.isCallback(window.location.hash);
    authContext.handleWindowCallback();    
    if (isCallback && !authContext.getLoginError()) {
        window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
    }    
    // If not logged in force login
    var user = authContext.getCachedUser();
    if (user) {
        // Logged in already
        console.log(user);
    } 
    else {
        
        authContext.login();
    }    
    // Acquire token for Files resource.
    authContext.acquireToken(config.endpoints. AzureApiUri, function (error, token) {
        // Handle ADAL Errors.
        if (error || !token) {
            console.log('ADAL error occurred: ' + error);
            return;
        }
        var ApiUri = "https://xxxxxxxxx.azurewebsites.net/api/Get";

        $.ajax({
            type: "GET",
            url: ApiUri,
            headers: {
                'Authorization': 'Bearer ' + token,
            }
        }).done(function (response) {
            console.log('Successfully called API.');
            console.log(response);
            
        }).fail(function () {
            console.log('Calling API failed.');
           
        });
    });
}
</script>
<input type='button' value='Call Azure API' onclick=" CallAzureAPI ();"/>

此解决方案在一段时间后有效(后来我发现 AAD cookie 已过期)我们收到此错误“由于超时令牌更新操作失败”,

我做了一些研究,我发现他 getCachedUser 或 getUser 方法查看浏览器存储 id_token 和 returns 如果缓存中有令牌,则为非空用户。但它不会查看令牌过期时间。 这里发生的事情是因为使用了 localStorage,当一个人重新打开浏览器时,令牌将保留在缓存中(因此 getCachedUser returns 是一个非空对象)但是 AAD cookie 已过期(除非用户检查了 keep me登录时已登录复选框)。由于 cookie 已过期,因此获取令牌调用失败并出现 "login required" 错误。

因此我检查了解决方法,让我保持登录状态 复选框在登录时有效。