从在线使用SharePoint安全Azure API

时间:2016-12-13 13:05:03

标签: azure authentication sharepoint-online azure-api-apps adal.js

我开发了具有身份验证功能的Azure API应用程序,使用Azure Active Directory登录,我需要在线使用此API,I
我需要验证和使用azure API,没有signin-prompt,应该在脚本中处理所有事情 需要使用ADAL.js来验证安全API,我找不到关于JavaScript代码的任何好的参考,我想知道是否有人有一个很好的参考JavaScript代码应该是什么样的?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

创建和配置API

  1. 创建azure API
  2. 以azure
  3. 发布您的azure API
  4. 浏览到azure portal,选择您的API应用程序,选择身份验证/授权

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

    • 请求我们未经过身份验证时要采取的措施:使用Azure词典登录

    • 身份验证提供商: Express enter image description here

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

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

    1. 单击将联合到您办公室365的目录(或您要调用azure API的任何源,该API使用与您为API身份验证配置的相同的azure活动目录)
    2. 单击应用程序,您将在列表中找到使用Express方法创建的AD应用程序,如我们在步骤nr.3中讨论的那样
    3. 现在我们需要在AAD中创建新的应用程序,这将是我们从Office 365到Azure API的通信渠道,点击页面上的ADD
    4. 输入名称并选择“WEB APPLICATION AND / OR WEB AP”选项
    5. 对于登录网址,请输入您计划从中调用Azure API的SharePoint在线网址
    6. 对于 APP ID UR L,请输入唯一网址,这将用作您应用的唯一逻辑标识符。
    7. 创建应用后,点击配置,复制稍后将使用的客户端ID
    8. 对其他应用程序的权限下,点击“添加应用程序”,在下一页上选择“所有应用程序”,然后选择Azure在步骤nr.8中仔细检查并确认
    9. 的API应用程序
    10. 您将被重定向回配置页面,在对其他应用程序的权限下,现在您看到此处列出了您的azure API应用程序,点击委派权限,选择访问应用
    11. 在页面底部,点击管理清单>下载演出 t。
    12. 将文件下载到可以编辑的位置。
    13. 在下载的清单文件中,搜索 oauth2AllowImplicitFlow 属性。将此属性的值从 false 更改为 true ,然后保存该文件。
    14. 点击管理清单>上传清单,并上传您在上一步中更新的文件。
    15. Azure管理门户,选择设置并复制相关AAD的AAD订阅ID enter image description here
    16. 从SharePoint Online调用Azure API

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

      1. 编辑页面并添加脚本编辑器Web部件
      2. 添加以下脚本 ·subscriptionId,参见步骤nr.20 ·clientId见步骤nr.13
      3. <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的浏览器存储,如果缓存中有令牌,则返回非null用户。但它不会查看令牌到期时间。 这里发生的事情是因为使用了localStorage,当重新打开浏览器时令牌被保存在缓存中(因此getCachedUser返回一个非空对象)但AAD cookie已过期(除非用户选中了保持登录状态复选框)在登录)。由于cookie已过期,因此获取令牌调用失败,并显示“需要登录”错误。

        为了解决这个问题,我在登录时选中了让我登录复选框,并且它有效。

答案 1 :(得分:0)

可以使用JavaScript在线调用Azure AD保护的Web API,但这非常复杂。

以下是供您参考的步骤:

  1. 开发受Azure AD保护的Web API
  2. 在同一租户上注册本机应用
  3. 为本机应用
  4. 启用隐含流
  5. 授予本机应用程序以从Azure门户访问Web API
  6. 使用本地应用的admin_consent授予组织权限
  7. 在Web API项目中为OAuth 2.0请求的重新编辑页面开发网页
  8. 使用windows.postMessage在网页中编写代码,将令牌发布到父页面

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

  10. &#13;
    &#13;
    <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>
    &#13;
    &#13;
    &#13;

    这是一个帮助理解进展的图: enter image description here