2016-06-20 5 views
0

Web API https://dev.office.com/app-registrationを登録しました。私はsign URL localhost:8000とRedirectURIをlocalhost:8000としていました。Service to ServiceコールとグラフAPi

これ以降、グラフAPIにアクセスするためのコンソールアプリケーションを作成しました。ここにコードがあります。しかし、それは動作しません。エラー "アクセスが拒否されました"が表示されます。

ここに何か不足していますか?

もう1つ、私はaccess_tokenをチェックして、そこにユーザー情報は表示されません。 string clientId = "<>"; string clientsecret = "<>"; 文字列テナント= "my.com";

 var authUri = "https://login.microsoftonline.com/" + tenant + "/oauth2/token"; 
     var RESOURCE_URL = "https://graph.microsoft.com"; 

     HttpClient client = new HttpClient(); 
     var authContext = new AuthenticationContext(authUri); 
     var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret); 
      var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result; 
      Console.WriteLine(result.AccessToken.ToString()); 

     client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken); 
     var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json"); 
     var response = client.GetAsync("https://graph.microsoft.com/v1.0/users/ankushb/calendar/events").Result; 
    // var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result; 
     Console.WriteLine(response.Content.ReadAsStringAsync().Result); 

答えて

0

Azure ADが使用するOAuth2には、2つの基本的な認証フローがあります。

最初はauthorization code grant flowで、これはネイティブクライアントとウェブサイトによってWeb APIにアクセスしました。このフローでは、ユーザーはクライアントアプリケーションへのアクセスを委任します。

第2は、Webサービス(機密クライアント)が、ユーザーを偽装するのではなく、別のWebサービスを呼び出すときに自身の資格情報を使用して認証することを許可します。このシナリオでは、クライアントは通常、中間層のWebサービス、デーモンサービス、またはWebサイトです。

上記のコードでは、クライアントクレデンシャルの許可フローを使用しているため、ユーザー情報が存在しません。あなたのシナリオでは

、あなたはネイティブアプリを登録する(コンソールアプリケーションは、トークンを要求する秘密を使用してはならない機密のクライアントではありません)、ユーザーがサインイン可能にするために認可コードグラント流れを使用する必要があります彼らのアカウントでコンソールアプリケーションでこのフローを使用するには、Webダイアログでログインインページに移動し、アクセストークンを要求する認証コードを取得する必要があります。ここで

は、認証コードの助成金の流れでアプリを認証するためのサンプルです:

var oauth = new OauthConfiguration 
     { 
      Authority = "https://login.microsoftonline.com", 
      Tenant = "common", 
      ClientId = "{clientId}", 
      RedirectURI = "{redirectURL}", 
      Secret = "" 
     }; 
     var tokenResponse = new OAuth2.OauthWebAuthHelper(oauth).AcquireTokenWithResource("https://graph.microsoft.com"); 
     var accessToken = tokenResponse.GetValue("access_token").Value<string>(); 
     var refreshToken = tokenResponse.GetValue("refresh_token").Value<string>(); 


namespace OAuth2 
{ 
public class OauthWebAuthHelper 
{ 
    public enum Version 
    { 
     V1 = 1, 
     V2 = 2 
    } 

    private OauthConfiguration _configuration; 

    private const string OAUTH2_AUTHORIZE_V1_SUFFIX = @"oauth2/"; 

    private const string OAUTH2_AUTHORIZE_V2_SUFFIX = @"oauth2/v2.0"; 

    private string _authorizeSuffix; 

    public OauthWebAuthHelper(OauthConfiguration configuration, Version version = Version.V1) 
    { 
     _configuration = configuration; 

     switch (version) 
     { 
      case Version.V1: _authorizeSuffix = OAUTH2_AUTHORIZE_V1_SUFFIX; break; 

      case Version.V2: _authorizeSuffix = OAUTH2_AUTHORIZE_V2_SUFFIX; break; 
     } 
    } 

    public void LogOut() 
    { 
     var dialog = new WebBrowserDialog(); 

     dialog.Open(string.Format("{0}/logout", EndPointUrl)); 
    } 

    protected string EndPointUrl 
    { 
     get 
     { 
      return string.Format("{0}/{1}/{2}", _configuration.Authority, _configuration.Tenant, _authorizeSuffix); 
     } 
    } 


    public JObject GetAuthorizationCode() 
    { 
     JObject response = new JObject(); 

     var parameters = new Dictionary<string, string> 
      { 
       { "response_type", "code" }, 
       { "client_id", _configuration.ClientId }, 
       { "redirect_uri", _configuration.RedirectURI }, 
       { "prompt", "login"} 
      }; 

     var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters)); 

     var dialog = new WebBrowserDialog(); 

     dialog.OnNavigated((sender, arg) => 
     { 
      if (arg.Url.AbsoluteUri.StartsWith(_configuration.RedirectURI)) 
      { 
       var collection = HttpUtility.ParseQueryString(arg.Url.Query); 

       foreach (var key in collection.AllKeys) 
       { 
        response.Add(key, collection[key]); 
       } 

       dialog.Close(); 
      } 
     }); 

     dialog.Open(requestUrl); 

     return response; 
    } 


    public JObject GetAuthorizationCode(string scope) 
    { 
     JObject response = new JObject(); 

     var parameters = new Dictionary<string, string> 
      { 
       { "response_type", "code" }, 
       { "client_id", _configuration.ClientId }, 
       { "redirect_uri", _configuration.RedirectURI }, 
       { "prompt", "login"}, 
       { "scope", scope} 
      }; 

     var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters)); 

     var dialog = new WebBrowserDialog(); 

     dialog.OnNavigated((sender, arg) => 
     { 
      if (arg.Url.AbsoluteUri.StartsWith(_configuration.RedirectURI)) 
      { 
       var collection = HttpUtility.ParseQueryString(arg.Url.Query); 

       foreach (var key in collection.AllKeys) 
       { 
        response.Add(key, collection[key]); 
       } 

       dialog.Close(); 
      } 
     }); 

     dialog.Open(requestUrl); 

     return response; 
    } 

    public JObject AcquireTokenWithResource(string resource) 
    { 
     var codeResponse = GetAuthorizationCode(); 

     var code = codeResponse.GetValue("code").Value<string>(); 

     var parameters = new Dictionary<string, string> 
      { 
       { "resource", resource}, 
       { "client_id", _configuration.ClientId }, 
       { "code", code}, 
       { "grant_type", "authorization_code" }, 
       { "redirect_uri", _configuration.RedirectURI}, 
       { "client_secret",_configuration.Secret} 
      }; 

     var client = new HttpClient(); 

     var content = new StringContent(BuildQueryString(parameters), Encoding.GetEncoding("utf-8"), "application/x-www-form-urlencoded"); 

     var url = string.Format("{0}/token", EndPointUrl); 

     var response = client.PostAsync(url, content).Result; 

     var text = response.Content.ReadAsStringAsync().Result; 

     return JsonConvert.DeserializeObject(text) as JObject; 
    } 


    public JObject RefreshTokenWithResource(string refreshToken) 
    { 
     var parameters = new Dictionary<string, string> 
      { 
       { "client_id", _configuration.ClientId }, 
       { "refresh_token", refreshToken}, 
       { "grant_type", "refresh_token" } 
      }; 

     var client = new HttpClient(); 

     var content = new StringContent(BuildQueryString(parameters), Encoding.GetEncoding("utf-8"), "application/x-www-form-urlencoded"); 

     var url = string.Format("{0}/token", EndPointUrl); 

     var response = client.PostAsync(url, content).Result; 

     var text = response.Content.ReadAsStringAsync().Result; 

     return JsonConvert.DeserializeObject(text) as JObject; 
    } 

    public JObject AcquireTokenWithScope(string scope) 
    { 
     var codeResponse = GetAuthorizationCode(scope); 

     var code = codeResponse.GetValue("code").Value<string>(); 

     var parameters = new Dictionary<string, string> 
      { 
       { "client_id", _configuration.ClientId }, 
       { "code", code}, 
       { "grant_type", "authorization_code" }, 
       { "redirect_uri", _configuration.RedirectURI}, 
      }; 

     var client = new HttpClient(); 

     var content = new StringContent(BuildQueryString(parameters), Encoding.GetEncoding("utf-8"), "application/x-www-form-urlencoded"); 

     var url = string.Format("{0}/token", EndPointUrl); 

     var response = client.PostAsync(url, content).Result; 

     var text = response.Content.ReadAsStringAsync().Result; 

     return JsonConvert.DeserializeObject(text) as JObject; 
    } 

    private string BuildQueryString(IDictionary<string, string> parameters) 
    { 
     var list = new List<string>(); 

     foreach (var parameter in parameters) 
     { 
      if (!string.IsNullOrEmpty(parameter.Value)) 
       list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value))); 
     } 

     return string.Join("&", list); 
    } 
} 

public class OauthConfiguration 
{ 
    public string Authority { get; set; } 

    public string Tenant { get; set; } 

    public string ClientId { get; set; } 

    public string RedirectURI { get; set; } 

    public string Secret { get; set; } 
} 

public class WebBrowserDialog 
{ 
    private const int DEFAULT_WIDTH = 400; 

    private const int DEFAULT_HEIGHT = 500; 

    private Form _displayLoginForm; 

    private string _title; 

    private WebBrowser _browser; 

    private WebBrowserNavigatedEventHandler _webBrowserNavigatedEventHandler; 

    public WebBrowserDialog() 
    { 
     _title = "OAuth Basic"; 

     _browser = new WebBrowser(); 

     _browser.Width = DEFAULT_WIDTH; 

     _browser.Height = DEFAULT_HEIGHT; 

     _browser.Navigated += WebBrowserNavigatedEventHandler; 

     _displayLoginForm = new Form(); 

     _displayLoginForm.SuspendLayout(); 

     _displayLoginForm.Width = DEFAULT_WIDTH; 

     _displayLoginForm.Height = DEFAULT_HEIGHT; 

     _displayLoginForm.Text = _title; 

     _displayLoginForm.Controls.Add(_browser); 

     _displayLoginForm.ResumeLayout(false); 
    } 


    public void OnNavigated(WebBrowserNavigatedEventHandler handler) 
    { 
     _webBrowserNavigatedEventHandler = handler; 
    } 

    protected void WebBrowserNavigatedEventHandler(object sender, WebBrowserNavigatedEventArgs e) 
    { 
     if(_webBrowserNavigatedEventHandler != null) 
     { 
      _webBrowserNavigatedEventHandler.Invoke(sender, e); 
     } 
    } 

    public void Open(string url) 
    { 
     _browser.Navigate(url); 

     _displayLoginForm.ShowDialog(); 
    } 

    public void Close() 
    { 
     _displayLoginForm.Close(); 
    } 
} 
} 

そして、あなたはhereからMicrosoftグラフについてのより多くのサンプルを得ることができます。