Créer des compléments SharePoint hébergés par un fournisseur pour accéder aux données SAP à l’aide de la Passerelle SAP pour Microsoft

You can create a SharePoint Add-in that reads and writes SAP data, and optionally reads and writes SharePoint data, by using the SAP Gateway for Microsoft and the Azure Active Directory Authentication Library for .NET. This article provides the procedures for how you can design the SharePoint Add-in to get authorized access to SAP.

Conditions requises

Voici les conditions préalables aux procédures décrites dans cet article :

Comprendre l’authentification et l’autorisation à la Passerelle SAP pour Microsoft et SharePoint

OAuth 2.0 in Azure AD enables applications to access multiple resources hosted by Azure, and SAP Gateway for Microsoft is one of them. With OAuth 2.0, applications, in addition to users, are security principals. Application principals require authentication and authorization to protected resources in addition to (and sometimes instead of) users.

The process involves an OAuth "flow" in which the application, which can be a SharePoint Add-in, obtains an access token (and refresh token) that is accepted by all of the Azure-hosted services and applications that are configured to use Azure AD as an OAuth 2.0 authorization server. The process is very similar to the way that the remote components of a provider-hosted SharePoint Add-in gets authorization to SharePoint as described in Creating SharePoint Add-ins that use low-trust authorization and its child articles. However, the ACS authorization system uses Azure Access Control Service (ACS) as the trusted token issuer rather than Azure AD.

Conseil

If your SharePoint Add-in accesses SharePoint in addition to accessing SAP Gateway for Microsoft, it needs to use both systems: Azure AD to get an access token to SAP Gateway for Microsoft, and the ACS authorization system to get an access token to SharePoint. The tokens from the two sources are not interchangeable. For more information, see Add SharePoint access to the ASP.NET application (optional).

Important

Azure Access Control (ACS), a service of Azure Active Directory (Azure AD), will be retired on November 7, 2018. This retirement does not impact the SharePoint Add-in model, which uses the https://accounts.accesscontrol.windows.net hostname (which is not impacted by this retirement). For more information, see Impact of Azure Access Control retirement for SharePoint Add-ins.

Pour obtenir une description détaillée et un diagramme du flux OAuth utilisé par OAuth 2.0 dans Azure AD, reportez-vous à la rubrique Autoriser l’accès aux applications web à l’aide de OAuth 2.0 et d’Azure Active Directory.

Pour une description similaire et un diagramme du flux permettant d’accéder à SharePoint, reportez-vous aux étapes décrites dans le flux de jeton de contexte.

Création du complément SharePoint

Création de la solution Visual Studio

  1. Create a SharePoint Add-in project in Visual Studio with the following steps. (The continuing example in this article assumes you are using C#, but you can start a SharePoint Add-in project in the Visual Basic section of the new project templates as well.)

    1. In the New SharePoint Add-in Wizard, name the project, and select OK. For the continuing example, use SAP2SharePoint.
    2. Specify the domain URL of your Office 365 Developer Site (including a final forward slash) as the debugging site; for example, https://<O365_domain>.sharepoint.com/. Specify Provider-hosted as the add-in type, and then select Next.
    3. Select a project type. For the continuing example, select ASP.NET Web Forms Application. (You can also make ASP.NET MVC applications that access SAP Gateway for Microsoft.) Select Next.
    4. Select Azure ACS as the authentication system. (Your SharePoint Add-in uses this system if it accesses SharePoint. It does not use this system when it accesses SAP Gateway for Microsoft.) Select Finish.
  2. After the project is created, you are prompted to sign in to the Office 365 account. Use the credentials of an account administrator; for example Bob@<O365_domain>.onmicrosoft.com.

  3. There are two projects in the Visual Studio solution: the SharePoint Add-in proper project and an ASP.NET web forms project. Add the Active Directory Authentication Library (ADAL) package to the ASP.NET project with these steps:

    1. Cliquez avec le bouton droit sur le dossier Références dans le projet ASP.NET (nommé SAP2SharePointWeb dans l’exemple de cet article) et sélectionnez Gérer les packages NuGet.
    2. In the dialog that opens, select Online on the left. Enter Microsoft.IdentityModel.Clients.ActiveDirectory in the search box.
    3. Lorsque la bibliothèque ADAL apparaît dans les résultats de la recherche, sélectionnez le bouton Installer et acceptez la licence lorsque vous y êtes invité.
  4. Ajoutez le package Json.net au projet ASP.NET en procédant comme suit :

    1. Enter Json.net in the search box. If this produces too many hits, try searching on Newtonsoft.json.
    2. Lorsque Json.net apparaît dans les résultats de la recherche, cliquez sur le bouton Installer.
  5. Sélectionnez Fermer.

Enregistrement de votre application web Azure AD

  1. Connectez-vous ? Portail Azure avec votre compte administrateur Azure.

Notes

Pour des raisons de sécurité, nous vous recommandons de ne pas utiliser un compte Administrateur lors du développement de compléments.

  1. Sélectionnez Active Directory sur la gauche.

  2. Sélectionnez votre annuaire.

  3. Dans la barre de navigation supérieure, sélectionnez APPLICATIONS.

  4. Sélectionnez Ajouter dans la barre d’outils en bas de l’écran.

  5. Dans la boîte de dialogue qui apparaît, sélectionnez Ajouter une application développée par mon organisation.

  6. In the ADD APPLICATION dialog, give the application a name. For the continuing example, use ContosoAutomobileCollection.

  7. Sélectionnez Application web et/ou API web comme type d’application, puis cliquez sur le bouton Flèche droite.

  8. On the second page of the dialog, use the SSL debugging URL from the ASP.NET project in the Visual Studio solution as the SIGN-ON URL. You can find the URL using the following steps. (You need to register the add-in initially with the debugging URL so that you can run the Visual Studio debugger (F5). When your add-in is ready for staging, you will re-register it with its staging Azure website URL. See Modify the add-in and stage it to Azure and Office 365.)

    1. Mettez en surbrillance le projet ASP.NET dans l’Explorateur de solutions.
    2. In the Properties window, copy the value of the SSL URL property. An example is https://localhost:44300/.
    3. Collez-la dans le champ URL de connexion dans la boîte de dialogue Ajouter une application.
  9. Pour l’URI ID d’application, n’attribuez à l’application qu’un seul URI, comme le nom de l’application ajouté à la fin de l’URL SSL. Par exemple, https://localhost:44300/ContosoAutomobileCollection.

  10. Select the checkmark button. The Azure dashboard for the application opens with a success message.

  11. Sélectionnez Configurer en haut de la page.

  12. Faites défiler jusqu’à l’ID client et copiez-le. Vous en aurez besoin pour une procédure ultérieure.

  13. In the keys section, create a key. It won't appear initially. Select SAVE at the bottom of the page and the key will be visible. Make a copy of it. You will need it for a later procedure.

  14. Faites défiler jusqu’à Autorisations pour d’autres applications et sélectionnez votre application de service de la Passerelle SAP pour Microsoft.

  15. Ouvrez la liste déroulante Autorisations déléguées et activez les cases pour les autorisations d’accès au service de la Passerelle SAP pour Microsoft qui seront nécessaires à votre complément SharePoint.

  16. Sélectionnez ENREGISTRER en bas de l’écran.

Pour configurer l’application pour communiquer avec Azure AD

  1. Dans Visual Studio, ouvrez le fichier web.config dans le projet ASP.NET.
  2. In the <appSettings> section, the Office Developer Tools for Visual Studio have added elements for the ClientID and ClientSecret of the SharePoint Add-in. (These are used in the Azure ACS authorization system if the ASP.NET application accesses SharePoint. You can ignore them for the continuing example, but do not delete them. They are required in provider-hosted SharePoint Add-ins even if the add-in is not accessing SharePoint data. Their values change each time you select F5 in Visual Studio.)

Add the following two elements to the section. These are used by the application to authenticate to Azure AD. (Remember that applications, as well as users, are security principals in OAuth-based authentication and authorization systems.)

<add key="ida:ClientID" value="" />
<add key="ida:ClientKey" value="" />
  1. Insert the Client ID that you saved from your Azure AD directory in the earlier procedure as the value of the ida:ClientID key. Leave the casing and punctuation exactly as you copied it, and be careful not to include a space character at the beginning or end of the value. For the ida:ClientKey key, use the key that you saved from the directory. Again, be careful not to introduce any space characters or change the value in any way. The <appSettings> section should now look something like the following (the ClientId value may have a GUID or an empty string):

    <appSettings>
      <add key="ClientId" value="" />
      <add key="ClientSecret" value="LypZu2yVajlHfPLRn5J2hBrwCk5aBOHxE4PtKCjIQkk=" />
      <add key="ida:ClientID" value="4da99afe-08b5-4bce-bc66-5356482ec2df" />
      <add key="ida:ClientKey" value="URwh/oiPay/b5jJWYHgkVdoE/x7gq3zZdtcl/cG14ss=" />
    </appSettings>
    

    Notes

    Your application is known to Azure AD by the "localhost" URL you used to register it. The client ID and client key are associated with that identity. When you are ready to stage your application to an Azure website, you will re-register it with a new URL.

  2. Still in the appSettings section, add an Authority key and set its value to the Office 365 domain (some_domain.onmicrosoft.com) of your organizational account. In the continuing example, the organizational account is Bob@<O365_domain>.onmicrosoft.com, so the authority is <O365_domain>.onmicrosoft.com.

    <add key="Authority" value="<O365_domain>.onmicrosoft.com" />
    
  3. Still in the appSettings section, add an AppRedirectUrl key and set its value to the page that the user's browser should be redirected to after the ASP.NET add-in has obtained an authorization code from Azure AD. Usually, this is the same page that the user was on when the call to Azure AD was made. In the continuing example, use the SSL URL value with "/Pages/Default.aspx" appended to it as shown in the following code (this is another value that you will change for staging):

    <add key="AppRedirectUrl" value="https://localhost:44322/Pages/Default.aspx" />
    
  4. Still in the appSettings section, add a ResourceUrl key and set its value to the APP ID URI of SAP Gateway for Microsoft (not the APP ID URI of your ASP.NET application). Obtain this value from the SAP Gateway for Microsoft administrator. The following is an example.

    <add key="ResourceUrl" value="http://<SAP_gateway_domain>.cloudapp.net/" />
    

    La section <appSettings> doit maintenant ressembler à ceci :

    <appSettings>
      <add key="ClientId" value="06af1059-8916-4851-a271-2705e8cf53c6" />
      <add key="ClientSecret" value="LypZu2yVajlHfPLRn5J2hBrwCk5aBOHxE4PtKCjIQkk=" />
      <add key="ida:ClientID" value="4da99afe-08b5-4bce-bc66-5356482ec2df" />
      <add key="ida:ClientKey" value="URwh/oiPay/b5jJWYHgkVdoE/x7gq3zZdtcl/cG14ss=" />
      <add key="Authority" value="<O365_domain>.onmicrosoft.com" />
      <add key="AppRedirectUrl" value="https://localhost:44322/Pages/Default.aspx" />
      <add key="ResourceUrl" value="http://<SAP_gateway_domain>.cloudapp.net/" />
    </appSettings>
    
  5. Enregistrez et fermez le fichier web.config.

    Conseil

    Do not leave the web.config file open when you run the Visual Studio debugger (F5). The Office Developer Tools for Visual Studio change the ClientId value (not the ida:ClientID) every time you select F5. This requires you to respond to a prompt to reload the web.config file, if it is open, before debugging can execute.

Ajout d’une classe d’assistance pour s’authentifier auprès d’Azure AD

  1. Cliquez avec le bouton droit sur le projet ASP.NET et utilisez le processus d’ajout de l’élément Visual Studio pour ajouter un nouveau fichier de classe au projet nommé AADAuthHelper.cs.

  2. Ajoutez les instructions using suivantes au fichier.

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using System.Configuration;
    using System.Web.UI;
    
  3. Modifiez le mot-clé d’accès en le passant de public à internal et ajoutez le mot-clé static à la déclaration de classe.

    internal static class AADAuthHelper
    
  4. Add the following fields to the class. These fields store information that your ASP.NET application uses to get access tokens from Azure AD.

    private static readonly string _authority = ConfigurationManager.AppSettings["Authority"];
    private static readonly string _appRedirectUrl = ConfigurationManager.AppSettings["AppRedirectUrl"];
    private static readonly string _resourceUrl = ConfigurationManager.AppSettings["ResourceUrl"];
    private static readonly string _clientId = ConfigurationManager.AppSettings["ida:ClientID"];
    private static readonly ClientCredential _clientCredential = new ClientCredential(
                              ConfigurationManager.AppSettings["ida:ClientID"],
                              ConfigurationManager.AppSettings["ida:ClientKey"]);
    
    private static readonly AuthenticationContext _authenticationContext =
                new AuthenticationContext("https://login.windows.net/common/" +
                                          ConfigurationManager.AppSettings["Authority"]);
    
  5. Add the following property to the class. This property holds the URL to the Azure AD sign-in screen.

    private static string AuthorizeUrl
    {
      get
      {
        return string.Format("https://login.windows.net/{0}/oauth2/authorize?response_type=code&amp;redirect_uri={1}&amp;client_id={2}&amp;state={3}",
            _authority,
            _appRedirectUrl,
            _clientId,
            Guid.NewGuid().ToString());
      }
    }
    
  6. Ajoutez les propriétés ci-dessous à la classe. Celles-ci mettent en cache les jetons d’accès et d’actualisation et vérifient leur validité.

    public static Tuple<string, DateTimeOffset> AccessToken
    {
      get {
        return HttpContext.Current.Session["AccessTokenWithExpireTime-" + _resourceUrl]
            as Tuple<string, DateTimeOffset>;
      }
    
      set { HttpContext.Current.Session["AccessTokenWithExpireTime-" + _resourceUrl] = value; }
    }
    
    private static bool IsAccessTokenValid
    {
      get
      {
        return AccessToken != null
          && !string.IsNullOrEmpty(AccessToken.Item1)
          && AccessToken.Item2 > DateTimeOffset.UtcNow;
      }
    }
    
    private static string RefreshToken
    {
      get { return HttpContext.Current.Session["RefreshToken" + _resourceUrl] as string; }
      set { HttpContext.Current.Session["RefreshToken-" + _resourceUrl] = value; }
    }
    
    private static bool IsRefreshTokenValid
    {
      get { return !string.IsNullOrEmpty(RefreshToken); }
    }
    
  7. Ajoutez les méthodes ci-dessous à la classe. Ces méthodes sont utilisées pour vérifier la validité du code d'autorisation et pour obtenir un jeton d'accès auprès d'Azure AD en utilisant soit un code d'authentification, soit un jeton d'actualisation.

    private static bool IsAuthorizationCodeNotNull(string authCode)
    {
      return !string.IsNullOrEmpty(authCode);
    }
    
    private static Tuple<Tuple<string,DateTimeOffset>,string> AcquireTokensUsingAuthCode(string authCode)
    {
      var authResult = _authenticationContext.AcquireTokenByAuthorizationCode(
                  authCode,
                  new Uri(_appRedirectUrl),
                  _clientCredential,
                  _resourceUrl);
    
      return new Tuple<Tuple<string, DateTimeOffset>, string>(
                  new Tuple<string, DateTimeOffset>(authResult.AccessToken, authResult.ExpiresOn),
                  authResult.RefreshToken);
    }
    
    private static Tuple<string, DateTimeOffset> RenewAccessTokenUsingRefreshToken()
    {
      var authResult = _authenticationContext.AcquireTokenByRefreshToken(
                          RefreshToken,
                          _clientCredential.OwnerId,
                          _clientCredential,
                          _resourceUrl);
    
      return new Tuple<string, DateTimeOffset>(authResult.AccessToken, authResult.ExpiresOn);
    }
    
  8. Add the following method to the class. It is called from the ASP.NET code-behind to obtain a valid access token before a call is made to get SAP data via SAP Gateway for Microsoft.

    internal static void EnsureValidAccessToken(Page page)
    {
      if (IsAccessTokenValid)
      {
        return;
      }
      else if (IsRefreshTokenValid)
      {
        AccessToken = RenewAccessTokenUsingRefreshToken();
        return;
      }
      else if (IsAuthorizationCodeNotNull(page.Request.QueryString["code"]))
      {
          Tuple<Tuple<string, DateTimeOffset>, string> tokens = null;
          try
          {
            tokens = AcquireTokensUsingAuthCode(page.Request.QueryString["code"]);
          }
          catch
          {
            page.Response.Redirect(AuthorizeUrl);
          }
          AccessToken = tokens.Item1;
          RefreshToken = tokens.Item2;
        return;
      }
      else
      {
        page.Response.Redirect(AuthorizeUrl);
      }
    }
    

Conseil

La AADAuthHelper classe ne gère que les erreurs minimales. Pour un SharePoint de qualité de production robuste, ajoutez une gestion des erreurs plus élevée, comme décrit dans ce nœud MSDN : Autoriser l’accès aux applications web à l’aide d’OAuth 2.0et Azure Active Directory .

Création de classes de modèle de données

  1. Create one or more classes to model the data that your add-in gets from SAP. In the continuing example, there is just one data model class. Right-click the ASP.NET project and use the Visual Studio item-adding process to add a new class file to the project named Automobile.cs.

  2. Ajoutez le code suivant dans le corps de la classe :

    public string Price;
    public string Brand;
    public string Model;
    public int Year;
    public string Engine;
    public int MaxPower;
    public string BodyStyle;
    public string Transmission;
    

Ajout de code-behind afin d’obtenir des données à partir de SAP via la Passerelle SAP pour Microsoft

  1. Ouvrez le fichier Default.aspx.cs, puis ajoutez-y les instructions using ci-dessous.

    using System.Net;
    using Newtonsoft.Json.Linq;
    
  2. Ajoutez une déclaration const à la classe Default dont la valeur est l'URL de base du point de terminaison OData SAP à laquelle le complément accédera. En voici un exemple :

    private const string SAP_ODATA_URL = @"https://<SAP_gateway_domain>.cloudapp.net:8081/perf/sap/opu/odata/sap/ZCAR_POC_SRV/";
    
  3. The Office Developer Tools for Visual Studio have added a Page_PreInit method and a Page_Load method. Comment out the code inside the Page_Load method and comment out the whole Page_Init method. This code is not used in this sample. (If your SharePoint Add-in is going to access SharePoint, restore this code. See Add SharePoint access to the ASP.NET application (optional).)

  4. Add the following line to the top of the Page_Load method. This eases the process of debugging because your ASP.NET application is communicating with SAP Gateway for Microsoft using SSL (HTTPS), but your "localhost:port" server is not configured to trust the certificate of SAP Gateway for Microsoft. Without this line of code, you would get an invalid certificate warning before Default.aspx opens. Some browsers allow you to click past this error, but some will not let you open Default.aspx at all.

    ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) => true;
    

    Important

    Delete this line when you are ready to deploy the ASP.NET application to staging. See Modify the add-in and stage it to Azure and Office 365.

  5. Ajoutez le code suivant à la méthode Page_Load. La chaîne que vous transmettez à la méthode GetSAPData est une requête OData.

    if (!IsPostBack)
    {
      GetSAPData("DataCollection?$top=3");
    }
    
  6. Ajoutez la méthode suivante à la classe Default. Cette méthode vérifie d'abord que la mise en cache du jeton d'accès possède un jeton d'accès valide qui a été obtenu à partir d'Azure AD. Il crée ensuite une demande HTTP GET dans laquelle le jeton d'accès est inclus puis l'envoie au point de terminaison OData SAP. Le résultat est renvoyé comme un objet JSON qui est converti en un objet de List.NET. Trois propriétés des éléments sont utilisées dans un tableau qui est lié à la DataListView.

    private void GetSAPData(string oDataQuery)
    {
      AADAuthHelper.EnsureValidAccessToken(this);
    
      using (WebClient client = new WebClient())
      {
        client.Headers[HttpRequestHeader.Accept] = "application/json";
        client.Headers[HttpRequestHeader.Authorization] = "Bearer " + AADAuthHelper.AccessToken.Item1;
        var jsonString = client.DownloadString(SAP_ODATA_URL + oDataQuery);
        var jsonValue = JObject.Parse(jsonString)["d"]["results"];
        var dataCol = jsonValue.ToObject<List<Automobile>>();
    
        var dataList = dataCol.Select((item) => {
            return item.Brand + " " + item.Model + " " + item.Price;
            }).ToArray();
    
        DataListView.DataSource = dataList;
        DataListView.DataBind();
      }
    }
    

Création de l’interface utilisateur

  1. Ouvrez le fichier Default.aspx et ajoutez le balisage suivant à l’élément form de la page :

    <div>
    <h3>Data from SAP via SAP Gateway for Microsoft</h3>
    
    <asp:ListView runat="server" ID="DataListView">
      <ItemTemplate>
        <tr runat="server">
          <td runat="server">
            <asp:Label ID="DataLabel" runat="server"
              Text="<%# Container.DataItem.ToString()%>" /><br />
          </td>
        </tr>
      </ItemTemplate>
    </asp:ListView>
    </div>
    
  2. Vous pouvez éventuellement donner à la page web l’« apparence » d’une page SharePoint à l’aide du contrôle Chrome SharePoint et de la feuille de style de site web hôte SharePoint.

Pour tester le complément avec F5 dans Visual Studio

  1. Dans Visual Studio, sélectionnez la touche F5.
  2. The first time that you use F5, you may be prompted to sign in to the Developer Site that you are using. Use the site administrator credentials. In the continuing example, it is Bob@<O365_domain>.onmicrosoft.com.
  3. The first time that you use F5, you are prompted to grant permissions to the add-in. Select Trust It.
  4. Après un court délai pendant l’obtention du jeton d’accès, la page Default.aspx s’ouvre. Vérifiez que les données SAP apparaissent.

Ajouter l’accès à SharePoint à l’application ASP.NET (facultatif)

Of course, your SharePoint Add-in doesn't have to expose only SAP data in a webpage launched from SharePoint. It can also create, read, update, and delete (CRUD) SharePoint data. Your code-behind can do this by using either the SharePoint client object model (CSOM) or the REST APIs of SharePoint. The CSOM is deployed as a pair of assemblies that the Office Developer Tools for Visual Studio automatically included in the ASP.NET project and set to Copy Local in Visual Studio so that they are included in the ASP.NET application package.

For information about using CSOM, start with Complete basic operations using SharePoint client library code. For information about using the REST APIs, start with Understanding and Using the SharePoint REST Interface.

Regardless of whether you use CSOM or the REST APIs to access SharePoint, your ASP.NET application must get an access token to SharePoint, just as it does to SAP Gateway for Microsoft. See Understand authentication and authorization to SAP Gateway for Microsoft and SharePoint earlier in this article.

La procédure ci-après fournit quelques recommandations de base sur la procédure, mais nous vous recommandons de lire tout d’abord les articles suivants :

Ajout de l’accès à SharePoint à l’application ASP.NET

  1. Ouvrez le fichier Default.aspx.cs et désaxistez la Page_PreInit méthode. En outre, vous ne pouvez pas ajouter de Office code Visual Studio outils de développement à la Page_Load méthode.

  2. If your SharePoint Add-in is going to access SharePoint data, you have to cache the SharePoint context token that is POSTed to the Default.aspx page when the add-in is launched in SharePoint. This is to ensure that the SharePoint context token is not lost when the browser is redirected following the Azure AD authentication. (You have several options for how to cache this context.) The Office Developer Tools for Visual Studio add a SharePointContext.cs file to the ASP.NET project that does most of the work. To use the session cache, you simply add the following code inside the if (!IsPostBack) block before the code that calls out to SAP Gateway for Microsoft.

    if (HttpContext.Current.Session["SharePointContext"] == null)
    {
        HttpContext.Current.Session["SharePointContext"]
            = SharePointContextProvider.Current.GetSharePointContext(Context);
    }
    
  3. Le fichier SharePointContext.cs effectue des appels vers un autre fichier que les outils de développement Office pour Visual Studio ajoutés au projet : TokenHelper.cs. Ce fichier fournit la plupart du code nécessaire pour obtenir et utiliser des jetons d’accès pour SharePoint. Cependant, il ne fournit aucun code pour renouveler un jeton d’accès ou d’actualisation expiré. Il ne contient pas non plus de code de mise en cache de jeton. Pour obtenir un SharePoint de production, vous devez ajouter ce code. La logique de mise en cache de l’étape précédente est un exemple. Votre code devrait également mettre en cache le jeton d’accès et le réutiliser jusqu’à son expiration. Lorsque le jeton d’accès expire, votre code doit utiliser le jeton d’actualisation pour obtenir un nouveau jeton d’accès.

  4. Add the data calls to SharePoint by using either CSOM or REST. The following example is a modification of CSOM code that Office Developer Tools for Visual Studio adds to the Page_Load method. In this example, the code has been moved to a separate method and it begins by retrieving the cached context token.

    private void GetSharePointTitle()
    {
        var spContext = HttpContext.Current.Session["SharePointContext"] as SharePointContext;
        using (var clientContext = spContext.CreateUserClientContextForSPHost())
        {
            clientContext.Load(clientContext.Web, web => web.Title);
            clientContext.ExecuteQuery();
            SharePointTitle.Text = "SharePoint website title is: " + clientContext.Web.Title;
        }
    }
    
  5. Ajoutez des éléments d’interface utilisateur pour rendre les données SharePoint. Voici le contrôle de code HTML référencé dans la méthode précédente :

    <h3>SharePoint title</h3>
    <asp:Label ID="SharePointTitle" runat="server"></asp:Label><br />
    

    Notes

    While you are debugging the SharePoint Add-in, the Office Developer Tools for Visual Studio re-register it with Azure ACS each time you select F5 in Visual Studio. When you stage the SharePoint Add-in, you have to give it a long-term registration. See Modify the add-in and stage it to Azure and Office 365.

Modification du complément et déploiement sur Azure et Office 365

Lorsque vous avez terminé le débogage du Complément SharePoint à l’aide de la touche F5 dans Visual Studio, vous devez déployer l’application ASP.NET dans un site web Azure réel.

Cr?er le site Web Azure

  1. Sur le portail Microsoft Azure, ouvrez sites web dans la barre de navigation de gauche.

  2. Sélectionnez NOUVEAU en bas de la page, puis, dans la boîte de dialogue NOUVEAU, sélectionnez site web |CRÉATION RAPIDE.

  3. Entrez un nom de domaine et sélectionnez CRÉER un site web. Copiez l’URL du nouveau site. Il a la forme my_domain.azurewebsites.net.

Modification du code et du balisage dans l’application

  1. Dans Visual Studio, supprimez la ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) => true; ligne du fichier Default.aspx.cs.
  2. Ouvrez leweb.config du projet ASP.NET et modifiez la partie domaine de la valeur de la clé dans la section en domaine du site web AppRedirectUrl appSettings Azure. Par exemple, <add key="AppRedirectUrl" value="https://localhost:44322/Pages/Default.aspx" /> changez en <add key="AppRedirectUrl" value="https://my_domain.azurewebsites.net/Pages/Default.aspx" /> .
  3. Cliquez avec le bouton droit surAppManifest.xml fichier dans le projet SharePoint de l’utilisateur, puis sélectionnez Afficher le code.
  4. Dans la valeur, remplacez la chaîne par le domaine complet du site web Azure, y compris le StartPage protocole ; par ~remoteAppUrl https://my_domain.azurewebsites.net exemple. La valeur StartPage entière doit maintenant être (généralement, la valeur est exactement la même que la valeur de la clé dans https://my_domain.azurewebsites.net/Pages/Default.aspx le StartPage AppRedirectUrl web.config fichier).

Modification de l’inscription à Azure AD et inscription du complément dans ACS

  1. Connectez-vous ? Portail Azure avec votre compte administrateur Azure.

  2. Sélectionnez Active Directory sur la gauche.

  3. Sélectionnez votre annuaire.

  4. Dans la barre de navigation supérieure, sélectionnez APPLICATIONS.

  5. Ouvrez l’application que vous avez créée. Dans l’exemple de cet article, il s’agit de ContosoAutomobileCollection.

  6. Pour chacune des valeurs suivantes, modifiez la partie « localhost:port » de la valeur pour le domaine de votre nouveau site web Azure :

    • URL DE CONNEXION
    • URI ID D’APPLICATION
    • URL DE RÉPONSE

    Par exemple, si l’URI ID D’APPLICATION est https://localhost:44304/ContosoAutomobileCollection, remplacez-le par https://<my_domain>.azurewebsites.net/ContosoAutomobileCollection.

  7. Sélectionnez ENREGISTRER en bas de l’écran.

  8. Register the add-in with Azure ACS. This must be done even if the add-in does not access SharePoint and does not use tokens from ACS because the same process also registers the add-in with the Add-in Management Service of the Office 365 subscription, which is a requirement. (It is called "Add-in Management Service" because SharePoint Add-ins were originally called "apps for SharePoint.")

    You perform the registration on the AppRegNew.aspx page of any SharePoint website in the Office 365 subscription. For details, see Register SharePoint Add-ins.

    As part of this process, you obtain a new Client ID and Client Secret. Insert these values in the web.config for the ClientId (not ida:ClientID) and ClientSecret keys.

    Avertissement

    If for any reason you select F5 after making this change, the Office Developer Tools for Visual Studio overwrites one or both of these values. For that reason, you should keep a record of the values obtained with AppRegNew.aspx and always verify that the values in the web.config are correct just before you publish the ASP.NET application.

Publication de l’application ASP.NET sur Azure et installation du complément sur SharePoint

  1. There are several ways to publish an ASP.NET application to an Azure website. For more information, see Local Git Deployment to Azure App Service.
  2. In Visual Studio, right-click the SharePoint Add-in project and select Package. On the Publish your add-in page that opens, select Package the add-in. File Explorer opens to the folder with the add-in package.
  3. Sign in to Office 365 as a global administrator, and navigate to the organization add-in catalog site collection. (If there isn't one, create it. See Use the Add-in Catalog to make custom business add-ins available for your SharePoint Online environment.)
  4. Téléchargez le package de complément dans le catalogue de compléments.
  5. Accédez à la page Contenu du site d’un site web de l’abonnement et sélectionnez Ajouter un complément.
  6. Sur la page Vos compléments, faites défiler jusqu’à la section Compléments que vous pouvez ajouter et sélectionnez l’icône de votre complément.
  7. Après avoir installé le complément, sélectionnez son icône sur la page Contenu du site pour lancer le complément.

Pour plus d’informations sur l’installation des compléments SharePoint, consultez Déploiement et installation de compléments SharePoint : méthodes et options.

Déploiement du complément en production

When you have finished all testing, you can deploy the add-in in production. This may require some changes.

  1. Si le domaine de production de l’application ASP.NET est différent du domaine intermédiaire, vous devez modifier la valeur dans leweb.configet la valeur dans le fichierAppManifest.xml, puis repackager le SharePoint AppRedirectUrl StartPage Add-in. Consultez la procédure pour modifier le code et le code dans l’application plus tôt dans cet article.
  2. The change in domain also requires that you edit the add-ins registration with Azure AD. See the procedure To modify the Azure AD registration and register the add-in with ACS earlier in this article.
  3. Pour modifier le domaine, vous devez également inscrire à nouveau le complément auprès du service ACS (et du service de gestion des compléments de l’abonnement) comme indiqué dans la même procédure. (Il n’existe aucun moyen de modifier l’inscription d’un add-in auprès d’ACS.) Toutefois, il n’est pas nécessaire de générer un nouvel ID client ou une nouvelle question secrète client sur la page AppRegNew.aspx. Vous pouvez copier les valeurs d’origine des clés (et non) duweb.configdans ClientId ida:ClientID le formulaire ClientSecret AppRegNew. Si vous en générez de nouvelles, n’oubliez pas de copier les nouvelles valeurs dans les clés web.config.

Voir aussi