从SharePoint在线使用Secure Azure API [英] Consume Secure Azure API from SharePoint online

查看:59
本文介绍了从SharePoint在线使用Secure Azure API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have developed Azure API app with authentication on feature, log in with Azure Active Directory, I need to consume this API from SharePoint online , I
I need to authenticate and consume the azure API, no signin-prompt, every thing should be handled in the script need to use ADAL.js to authenticate secure API ,I cannot find any good reference about the JavaScript code, I was wondering if anyone have a good reference how the JavaScript code should look like?

谢谢!

推荐答案

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

Here are the steps to call the azure hosted API from SharePoint online using JavaScript and ADAL.js library, no signing-prompt, everything should be handled in the script using ADAL.js to authenticate secure API

创建和配置API

  1. 创建azure API
  2. 以天蓝色发布您的天蓝色API
  3. 浏览到Azure门户,选择您的API应用程序,然后选择身份验证/授权

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

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

Action to take when request us not authenticated: Log in with Azure dictionary

身份验证提供者:快速

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

Now the API is protected with Azure AD, if you navigate your API via browser you will be prompted for login

  1. 单击将与您的Office 365联合的目录(或您要调用azure API的任何来源,该来源使用与您为API身份验证配置的相同azure活动目录)
  2. 单击应用程序",您将在我们通过步骤nr.3讨论的Express方法创建的列表中找到您的AD应用程序.
  3. 现在我们需要在AAD中创建新应用,这将是我们从Office 365到Azure API的通信渠道,单击页脚上的ADD
  4. 输入名称,然后选择"Web应用程序和/或WEB AP"选项
  5. 对于登录URL ,输入您打算从
  6. 调用Azure API的SharePoint在线网址.
  7. 对于 APP ID UR L,输入唯一的网址,该网址将用作您应用的唯一逻辑标识符.
  8. 创建应用后,点击配置",复制客户端ID ,以后将使用
  9. 对其他应用程序的权限下,单击"添加应用程序",在下一页上选择"所有应用程序 s",然后选择您的Azure您在步骤nr.8中仔细检查过的API应用,然后确认
  10. 您将被重定向回配置"页面,在对其他应用程序的权限下,您现在看到此处列出了您的azure API应用,单击已授予的权限,然后选择访问应用程序
  11. 在页面底部,单击管理清单>下载清单.
  12. 将文件下载到可以编辑的位置.
  13. 在下载的清单文件中,搜索 oauth2AllowImplicitFlow 属性.将此属性的值从 false 更改为 true ,然后保存文件.
  14. 点击管理清单>上传清单,然后上传在上一步中更新的文件.
  15. Azure管理门户,选择设置并复制相关AAD的AAD订阅ID
  1. Click on the Directory which will be federated to your office 365 (or any source you want to call azure API which uses the same azure active directory as your configured for you API authentication)
  2. Click on the Application, and you will find you AD app in the list which has been created with Express method as we discussed om step nr.3
  3. Now we need to create new app in AAD which will be our communication channel from office 365 to Azure API, Click on ADD on footer
  4. Enter name and select "WEB APPLICATION AND/OR WEB AP" option
  5. For Sign in URL enter your SharePoint online Url which you are planning to call Azure API from
  6. For APP ID URL, enter unique Url, this will be used as a unique logical identifier for your app.
  7. After the app created, click on Configure, copy the Client ID which will be used later­­
  8. Under Permission to other applications, Click "Add Application", on the next page select "All Apps" and select you Azure API app which you double checked in step nr.8, and confirm
  9. You will be redirected back to Configure page, Under Permission to other applications, now you see your azure API app is listed here, click on delegated permission, select the access to app
  10. At the bottom of the page, click Manage manifest > Download manifest.
  11. Download the file to a location where you can edit it.
  12. In the downloaded manifest file, search for the oauth2AllowImplicitFlow property. Change the value of this property from false to true, and then save the file.
  13. Click Manage manifest > Upload manifest, and upload the file that you updated in the preceding step.
  14. Azure management portal, select setting and copy your AAD subscription ID for related AAD

从SharePoint Online调用Azure API

完成上述步骤后,您可以从sharePoint在线调用azure API,该API使用上方的同一Active目录

Once the above steps have been done, you can call azure API from sharePoint online which is using same Active directory above

  1. 编辑页面并添加脚本编辑器Web部件
  2. 添加以下脚本·subscriptionId,请参阅步骤nr.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过期),我们收到此错误"令牌更新操作由于超时而失败",

This solution works though after some time ( later I found out when AAD cookie is expired ) we get this error "Token renewal operation failed due to timeout ",

我做了一些研究,发现他的getCachedUser或getUser方法在浏览器存储中查找id_token,如果缓存中有令牌,则返回非null用户.但是,它不会考虑令牌的到期时间.这里发生的是因为使用了localStorage,所以当一个人重新打开浏览器时令牌被保留在缓存中(因此getCachedUser返回一个非空对象),但是AAD cookie已过期(除非用户选中了当我保持登录状态"复选框)在登录).由于Cookie过期,因此获取令牌调用失败,并显示需要登录"错误.

I did some research and I found out he getCachedUser or getUser methods look into the browser storage for id_token and returns a non-null user if there is a token inside the cache. It does not look into the token expiration time though. What's happening here is since localStorage is used, tokens are preserved in the cache when one re-opens the browser (and hence getCachedUser returns a non-null object) but the AAD cookie is expired (unless user checked the keep me signed in checkbox when logging in). Since the cookie is expired, acquire token call fails with the "login required" error.

因此,我选中了变通办法,登录后保持登录状态复选框有效.

so as workaround I checked , keep me signed in checkbox when logging in and it works .

这篇关于从SharePoint在线使用Secure Azure API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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