KeiStory

C# .NET6 에서 Active Directory Authentication 사용하기

 

.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);

 

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band