2017-07-14 62 views
1

我从我的问题开始。如何使用Microsoft Graph使用Azure AD内部的应用程序注册来读取AAD中的数据?现在,细节...使用AAD App访问Microsoft Graph

我在Azure的Active Directory中创建一个应用程序的注册,并允许访问Microsoft图表有:

AAD portal with required permissions

其确切的应用具有以下权限:

  • 应用程序的权限
    • 阅读所有用户的相关人员名单和搜索导演Ÿ
    • 阅读所有用户的全部资料
  • 委托权限 (无)

我用下面的代码在我的ASP.NET MVC应用程序来对AAD验证我的网站:

public void SignIn() 
{ 
    if (!Request.IsAuthenticated) 
    { 
     HttpContext.GetOwinContext().Authentication.Challenge(
      new AuthenticationProperties 
      { 
       RedirectUri = "/" 
      }, 
      OpenIdConnectAuthenticationDefaults.AuthenticationType); 
    } 
} 

这几乎是组织认证的默认设置。这工作,我甚至可以从AAD轮廓读出我的用户信息:

private string GetUserName() 
{       
    var claimsPrincipal = ClaimsPrincipal.Current;   
    var firstName = claimsPrincipal.FindFirst(ClaimTypes.GivenName).Value; 
    var lastName = claimsPrincipal.FindFirst(ClaimTypes.Surname).Value; 
    return $"{firstName} {lastName}"; 
} 

现在我尝试使用微软图表来optain让说的头像图片。有一些官方MS样品可用here。但他们都依赖于当前预览的名为Microsoft.Identity.Client的NuGet包。另一件事是,MS要我注册我的应用程序Application Registration Portal这对我来说没有意义,因为我已经有一个注册的应用程序。

我已经试图从我的声明身份找回我的承载令牌和使用它的图形是这样的:

var ci = (System.Security.Claims.ClaimsIdentity)ClaimsPrincipal.Current.Identity; 
var token = ((System.IdentityModel.Tokens.BootstrapContext)ci.BootstrapContext).Token; 
var endpoint = "https://graph.microsoft.com/v1.0/me/photo/$value"; 
using (var client = new HttpClient()) 
{ 
    using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint)) 
    {      
     request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 
     var response = await client.SendAsync(request);     
     if (response.IsSuccessStatusCode) 
     { 
      return await response.Content.ReadAsStreamAsync(); 
     }      
    } 
} 
return null; 

但是这给了我401

回答

0

你需要得到与ADAL使用令牌你的应用的客户端ID和秘密。

您可以从的NuGet获得ADAL:https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/

如:

string authority = "https://login.microsoftonline.com/your-tenant-id"; 
var authenticationContext = new AuthenticationContext(authority); 

string clientId = "your-app-client-id"; 
string clientSecret = "yourappclientsecret"; 
var clientCredential = new ClientCredential(clientId, clientSecret); 

string resource = "https://graph.microsoft.com"; 
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCredential); 

string accessToken = authenticationResult.AccessToken; 

更换您的租户-ID与Azure的AD租户ID或域名(例如mytenant.onmicrosoft.com) 。将您的应用客户端ID为的替换为在AAD中注册的应用的客户端ID /应用ID。使用为AAD中的应用程序创建的客户端密钥/密钥替换yourappclientsecret

我在示例中对它们进行了硬编码,以使其更容易遵循。在生产中,你不应该在代码中存储凭据。

相关问题