2016-06-20 2 views
0

웹 API https://dev.office.com/app-registration을 등록했습니다. 나는 기호 URL localhost : 8000과 RedirectURI를 localhost : 8000으로 유지했다.서비스 콜 서비스 및 그래프 APi

그런 다음 그래프 API에 액세스 할 콘솔 응용 프로그램을 만들었습니다. 여기에 코드가 있습니다. 그러나 그것은 작동하지 않습니다. "액세스가 거부되었습니다"라는 오류 메시지가 나타납니다.

여기에 누락 된 자료가 있습니까?

한 가지 더, 나는 access_token을 확인했는데 거기에 어떤 사용자 정보도 보지 못했습니다. string clientId = "<>"; 문자열 clientsecret = "<>"; string tenant = "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에는 두 가지 기본 인증 절차가 있습니다.

첫 번째는 authorization code grant flow으로, 원시 클라이언트와 웹 사이트에서 웹 API에 액세스하는 데 사용됩니다.이 흐름에서 사용자는 클라이언트 응용 프로그램에 대한 액세스 권한을 위임합니다.

둘째는 웹 서비스 (기밀 클라이언트)가 사용자를 가장하는 대신 다른 웹 서비스를 호출 할 때 자신의 자격 증명을 사용하여 인증 할 수 있도록 허용하는 Client Credentials grant flow입니다. 이 시나리오에서 클라이언트는 일반적으로 중간 계층 웹 서비스, 데몬 서비스 또는 웹 사이트입니다.

위의 코드는 클라이언트 자격 증명 부여 플로을 사용하고 있기 때문에 사용자 정보가 없습니다. 시나리오에서

, 당신은 네이티브 응용 프로그램을 등록해야하고 수 있도록을 흐름 인증 코드 부여를 사용 (콘솔 응용 프로그램 기밀 토큰를 요청하는 비밀을 사용해서는 안 클라이언트없는) 사용자는 로그인에 그들의 계정으로. 콘솔 응용 프로그램에서이 흐름을 사용하려면 웹 대화 상자에 로그인 페이지로 이동하여 액세스 토큰을 요청하는 인증 코드를 요청해야합니다. 여기

는 인증 코드 부여 흐름 응용 프로그램 인증하는 샘플입니다 :

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에서 마이크로 소프트 그래프에 대한 자세한 샘플을 얻을 수 있습니다.