728x90

아래의 .Net Frameork 버전의 코드를 .NET6 에서 코딩하게되면 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);

 

728x90
Posted by kjun.kr
,