.NET6 에서 Active Directory Authentication 사용하려면 PlatformParameters 부분에서 ICustomWebUi 를 요구합니다.
var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", "your app id", new Uri("urn:ietf:wg:oauth:2.0:oob"), new PlatformParameters(PromptBehavior.Auto));
.Net6 버전으로 바꾸면 아래와같습니다.
class CustomWebUi : ICustomWebUi
{
private readonly Dispatcher _dispatcher;
public CustomWebUi(Dispatcher dispatcher)
{
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher))
}
public Task<Uri> AcquireAuthorizationCodeAsync(Uri authorizationUri, Uri redirectUr
{
var tcs = new TaskCompletionSource<Uri>();
_dispatcher.InvokeAsync(() =>
{
var webView = new WebView();
var w = new Window
{
Title = "Auth",
WindowStyle = WindowStyle.ToolWindow,
Content = webView,
};
w.Loaded += (_, __) => webView.Navigate(authorizationUri);
webView.NavigationCompleted += (_, e) =>
{
System.Diagnostics.Debug.WriteLine(e.Uri);
if (e.Uri.Query.Contains("code="))
{
tcs.SetResult(e.Uri);
w.DialogResult = true;
w.Close();
}
if (e.Uri.Query.Contains("error="))
{
tcs.SetException(new Exception(e.Uri.Query));
w.DialogResult = false;
w.Close();
}
};
webView.UnsupportedUriSchemeIdentified += (_, e) =>
{
if (e.Uri.Query.Contains("code="))
{
tcs.SetResult(e.Uri);
w.DialogResult = true;
w.Close();
}
else
{
tcs.SetException(new Exception($"Unknown error: {e.Uri}"));
w.DialogResult = false;
w.Close();
}
};
if (w.ShowDialog() != true && !tcs.Task.IsCompleted)
{
tcs.SetException(new Exception("canceled"));
}
});
return tcs.Task;
}
}
사용
var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com",
"your app id",
new Uri("urn:ietf:wg:oauth:2.0:oob"),
new PlatformParameters(PromptBehavior.Auto, new CustomWebUi(Dispatcher)));
MessageBox.Show(result.AccessToken);
C# Edge 에서 지정한 Tab 닫도록 처리하기 (0) | 2024.04.24 |
---|---|
C# ExpandoObject 를 이용해 Dynamic 한 객체 만들기 (0) | 2024.04.24 |
C# WebView2 설치여부에 따라 설치되도록 처리하기 (0) | 2024.04.22 |
C# 작업표시줄 깜빡이게 하기 - FlashWindowEx (0) | 2024.04.22 |
C# HEIC 파일 PNG 로 변환하기 (0) | 2024.04.14 |