使用App Model V2访问日历

时间:2016-06-30 12:29:44

标签: azure microsoft-graph

我们在Azure中有一个关于ASP.NET的Web应用程序,我们希望能够访问当前用户的日历,以显示今天的事件和未读电子邮件的数量。我们的应用程序使用graph.microsoft.com默认"工作或学校帐户"使用Visual Studio创建的身份验证,但这不适用于App Model V2。

如何构建能够使用App Model V2进行身份验证并访问graph.microsoft.com的应用程序?

1 个答案:

答案 0 :(得分:0)

您需要使用Microsoft.IdentityModel.Clients.ActiveDirectory;

给出了一个很好的样本 https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview/

您需要为App Model V2应用程序采取的步骤是:

  1. 使用https://apps.dev.microsoft.com上的应用程序注册门户注册您的应用程序。记住为您注册的clientID和clientsecret。
  2. 在没有身份验证的情况下在VS2015中创建一个asp.net(匿名)
  3. 添加Nuget包Microsoft.IdentityModel.Clients.ActiveDirectory
  4. 使用Microsoft.IdentityModel.Clients.ActiveDirectory添加到控制器
  5. 您需要将代码作为私有成员
  6. 添加到您的代码中

    private static string [] scopes = {             “https://graph.microsoft.com/calendars.readwrite”};

    1. 添加以下设置添加到web.config

      <add key="ida:ClientID" value="..." />
      <add key="ida:ClientSecret" value="..." />
      
    2. 您必须创建2个额外的方法。一个用于登录,一个用于授权:

    3. 登入:

              public async Task<ActionResult> SignIn()
          {
              string authority = "https://login.microsoftonline.com/common/v2.0";
              string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
              AuthenticationContext authContext = new AuthenticationContext(authority);
      
              // The url in our app that Azure should redirect to after successful signin
              Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
      
              // Generate the parameterized URL for Azure signin
              Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, additionalScopes, clientId,
                  redirectUri, UserIdentifier.AnyUser, null);
      
              // Redirect the browser to the Azure signin page
              return Redirect(authUri.ToString());
          }
      

      授权:

              public async Task<ActionResult> Authorize()
          {
              // Get the 'code' parameter from the Azure redirect
              string authCode = Request.Params["code"];
      
              string authority = "https://login.microsoftonline.com/common/v2.0";
              string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
              string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"];
              AuthenticationContext authContext = new AuthenticationContext(authority);
      
              // The same url we specified in the auth code request
              Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
      
              // Use client ID and secret to establish app identity
              ClientCredential credential = new ClientCredential(clientId, clientSecret);
      
              try
              {
                  // Get the token
      
                  var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                      authCode, redirectUri, credential, scopes);
      
                  // Save the token in the session
                  Session["access_token"] = authResult.Token;
                  return Redirect(Url.Action("Tasks", "Home", null, Request.Url.Scheme));
              }
              catch (AdalException ex)
              {
                  return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
              }
          }
      

      accestoken处于会话状态。

      现在,您可以使用正确的accesstoken调用graph.microsoft.com并获取数据:

              private async Task<List<DisplayEvent>> GetEvents()
          {
              List<DisplayEvent> tasks = new List<DisplayEvent>();
      
              HttpClient httpClient = new HttpClient();
              var accessToken = (string)Session["access_token"];
      
              httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
              HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/beta/users/me/events");
      
              if (response.IsSuccessStatusCode)
              {
                  string s = await response.Content.ReadAsStringAsync();
                  JavaScriptSerializer serializer = new JavaScriptSerializer();
                  EventModels eventList = serializer.Deserialize<EventModels>(s);
      
                  foreach (EventModel v in eventList.value)
                  {
                      //Fill tasks will events
                  }
              }
              return tasks;
          }