2017-07-14 13 views
1

私は質問から始めます。 Azure ADの内部にあるアプリ登録を使用して、Microsoft Graphを使用して自分のAADからデータを読み取るにはどうすればよいですか?今すぐ詳細は...AAD AppでMicrosoft Graphにアクセス

私のAzure Active Directoryにアプリ登録を作成し、そこにマイクロソフトグラフへのアクセスを許可:

AAD portal with required permissions

であるためには、正確なアプリは、次の権限を持っています

  • アプリケーション権限
    • すべてのユーザーの関係者のリストを読み、ディレクターを検索Y
    • 読むすべてのユーザーの完全なプロファイル
  • 委任アクセス権 (なし)

私はAADに対する私のウェブサイトを認証するために私のASP.NET MVCアプリケーションに次のコードを使用します。

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するには、Microsoftグラフを使用しようとするアバター画像を言うことができます。利用可能ないくつかの公式MSサンプルがあるhere。しかし、それらのすべては現在というNuGetパッケージに依存しており、現在はプレビューされています。もう1つは、私がすでに登録済みのアプリを持っているので、私には意味がない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; 

しかし、これはあなたが使用してADALでトークンを取得する必要があり、私の401

答えて

0

を与えますあなたのアプリのクライアント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; 

(例えばmytenant.onmicrosoft.com)あなたのAzure ADテナントIDまたはドメイン名であなたのテナント-IDを交換してください。 your-app-client-idを、AADに登録されているアプリのクライアントID /アプリケーションIDに置き換えます。 yourappclientsecretを、AADのアプリ用に作成されたクライアントシークレット/キーに置き換えます。

この例では、わかりやすいようにハードコードしてあります。本番環境では、コードに資格情報を格納しないでください。

関連する問題