Skip to content

Instantly share code, notes, and snippets.

@chenxizhang
Created March 15, 2018 06:45
Show Gist options
  • Save chenxizhang/f8681ee759a463e250de0e10cbd6763a to your computer and use it in GitHub Desktop.
Save chenxizhang/f8681ee759a463e250de0e10cbd6763a to your computer and use it in GitHub Desktop.
Connect to Microsoft Graph use ADAL & Microsoft Graph SDK
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading.Tasks;
namespace MicrosoftGraphSampleUseADAL
{
//这个代码演示了如何使用ADAL和Microsoft Graph库来实现访问,并且分别实现了国际版和国内版
//作者:陈希章
class Program
{
static void Main(string[] args)
{
//国际版 1a7b2299-db59-4dbc-b469-22756728a833
//国内版 d64e46b8-6827-46d8-b70c-6b72aa1af48b
var config = new GallatinConfig();
var client = new GraphServiceClient(config.BaseUrl,new DelegateAuthenticationProvider(async request =>
{
var token = await GetAccessToken("d64e46b8-6827-46d8-b70c-6b72aa1af48b", "http://localhost", config);
request.Headers.Add("Authorization", $"Bearer {token}");
}));
var user = client.Me.Request().GetAsync();
Console.WriteLine(user.Result.DisplayName);
Console.Read();
}
interface IOffice365Config
{
string AuthorizationEndpoint { get; }
string ResourceUrl { get;}
string BaseUrl { get;}
}
class GallatinConfig : IOffice365Config
{
public string AuthorizationEndpoint => "https://login.chinacloudapi.cn/common/oauth2/authorize";
public string ResourceUrl => "https://microsoftgraph.chinacloudapi.cn";
public string BaseUrl => "https://microsoftgraph.chinacloudapi.cn/v1.0";
}
class GlobalConfig : IOffice365Config
{
public string AuthorizationEndpoint => "https://login.microsoftonline.com/common/oauth2/authorize";
public string ResourceUrl => "https://graph.microsoft.com";
public string BaseUrl => "https://graph.microsoft.com/v1.0";
}
static async Task<string> GetAccessToken(string clientId,string redirctUrl,IOffice365Config config) {
AuthenticationResult result = null;
var context = new AuthenticationContext(config.AuthorizationEndpoint);
try
{
result = await context.AcquireTokenSilentAsync(config.ResourceUrl, clientId);
}
catch (Exception)
{
result = await context.AcquireTokenAsync(config.ResourceUrl, clientId, new Uri(redirctUrl), new PlatformParameters(PromptBehavior.Auto));
}
return result.AccessToken;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment