使用App Model V2访问日历
问题描述:
我们在Azure中的ASP.NET上有一个web应用程序,我们想要访问当前用户到他的日历以显示今天的事件以及未读电子邮件的数量。我们有使用graph.microsoft.com的应用程序,该应用程序使用Visual Studio创建的默认“工作或学校帐户”身份验证,但这不适用于App Model V2。使用App Model V2访问日历
如何构建能够使用App Model V2进行身份验证并访问graph.microsoft.com的应用程序?
答
您需要使用Microsoft.IdentityModel.Clients.ActiveDirectory;
一个很好的样本中 https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview/
是因为你需要的应用型V2申请步骤是:
- 使用的应用程序注册门户注册应用程序上https://apps.dev.microsoft.com。记住为你注册的clientID和clientsecret。
- 创建VS2015无需验证一个asp.net(匿名)
- 添加NuGet包Microsoft.IdentityModel.Clients.ActiveDirectory
- 使用Microsoft.IdentityModel.Clients.ActiveDirectory添加到控制器
- 您需要到您的代码添加范围为私人构件
私人静态字符串[]范围= { “https://graph.microsoft.com/calendars.readwrite”};
-
添加添加以下设置的Web.config
<add key="ida:ClientID" value="..." /> <add key="ida:ClientSecret" value="..." />
你必须创建2种额外的方法。一个用于登入和一个用于认证:
签到:
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处于会话状态。
现在,您可以拨打graph.microsoft.com用正确的accessToken和获取数据:
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;
}