Skip to content

Instantly share code, notes, and snippets.

@chenxizhang
Created November 13, 2017 13:39
Show Gist options
  • Save chenxizhang/fa02813a084ac699971116dc7e8a9368 to your computer and use it in GitHub Desktop.
Save chenxizhang/fa02813a084ac699971116dc7e8a9368 to your computer and use it in GitHub Desktop.
这个范例代码演示了如何在Console Application中完整地实现Azure AD 2.0身份认证,并且保存身份。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using System.Net.Http;
/// <summary>
/// 这个范例代码演示了如何在Console Application中完整地实现Azure AD 2.0身份认证,并且保存身份。
/// 作者:陈希章
/// 时间:2017年11月13日
/// 说明:需要引用Microsoft.Identity.Client(MSAL,当前是prerelease状态),Microsoft.Graph这两个Package
/// </summary>
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
IUser user = null;
string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.txt";
object FileLock = new object();
var tokenCache = new TokenCache();
tokenCache.SetBeforeAccess((_args) => {
//反序列化
lock (FileLock)
{
_args.TokenCache.Deserialize(System.IO.File.Exists(CacheFilePath)
? System.IO.File.ReadAllBytes(CacheFilePath)
: null);
}
});
tokenCache.SetAfterAccess((_args) =>
{
//序列化
if (_args.TokenCache.HasStateChanged)
{
lock (FileLock)
{
System.IO.File.WriteAllBytes(CacheFilePath, _args.TokenCache.Serialize());
_args.TokenCache.HasStateChanged = false;
}
}
});
var client = new PublicClientApplication("a1d42c27-29c4-4e8b-b08c-1ee417f2aa40", "https://login.microsoftonline.com/common/oauth2/authorize", tokenCache);
if (client.Users != null && client.Users.Count() > 0)
user = client.Users.First();
var graph = new GraphServiceClient(new DelegateAuthenticationProvider(async(request)=> {
var scope = new string[] { "user.read","mail.read","mail.send" };
AuthenticationResult token = null;
try
{
token = await client.AcquireTokenSilentAsync(scope, user);
}
catch (Exception ex)
{
token = await client.AcquireTokenAsync(scope);
user = token.User;
}
request.Headers.Add("Authorization", $"Bearer {token.AccessToken}");
}));
var me = graph.Me.Request().GetAsync().Result;
Console.WriteLine(me.DisplayName);
var messages = graph.Me.Messages.Request().GetAsync().Result;
Console.WriteLine(string.Join(Environment.NewLine, messages.Select(x => x.Subject)));
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment