На данный момент наш главный приоритет — успешная аутентификация пользователей (в интерактивном режиме) в нашем клиенте Azure B2C. Это означает, что мы пытаемся убедиться в правильности как нашей базы кода, так и настройки стороны Azure. На данный момент мы столкнулись с проблемой: когда мы запускаем код как с URI перенаправления, так и с полномочиями, которые мы считаем правильными, мы получаем ошибки сценария. Когда мы удаляем URI перенаправления в коде, мы получаем пустой экран входа в систему, но когда мы опускаем центр, мы правильно аутентифицируемся в нашем клиенте, но без запуска наших пользовательских потоков. Когда мы пытаемся изменить эти значения, мы получаем исключение, сообщающее, что URI неверен. Мы протестировали наши пользовательские потоки в нашем клиенте Azure B2C и считаем, что они настроены правильно. Ниже мы прикрепили код, который мы сейчас выполняем, и снимок экрана с ошибкой скрипта.
Код: Выделить всё
/////////////// THISADDIN.CS ///////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace authtest_addin
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Authenticate.isAuthorizedUser = false;
Authenticate.AppCreation();
Task.Run(async () => await Authenticate.RunAuthentication());
//MessageBox.Show(Globals.ThisAddIn.Application.UserName);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
Код: Выделить всё
/////////////// AUTHENICATE.CS ////////////////////////////////
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.Identity.Client.NativeInterop;
namespace authtest_addin
{
internal class Authenticate
{
public static bool isAuthorizedUser;
private static IPublicClientApplication app;
private static readonly string clientID = "82d76b60-b6c5-4cb4-ac05-df77bece9feb";
private static readonly string tenantID = "c7afce06-4b73-4f1f-b069-9d611042a736";
public static string SignInPolicy = "B2C_1_SignUpSignIn"; // Replace with your user flow name
private static readonly string Tenant = "khordeveloperb2c.onmicrosoft.com";
public static string AuthorityBase = $"https://khordeveloperb2c.b2clogin.com/tfp/{Tenant}/";
private static readonly string redirectURI = "https://login.microsoftonline.com/common/oauth2/nativeclient";
public static async Task RunAuthentication()
{
await AuthenticateUser();
if (isAuthorizedUser)
{
MessageBox.Show("Authorized");
Globals.Ribbons.Ribbon1.authStatus.Label = "User Status: Authorized";
}
else
{
MessageBox.Show("Unauthorized");
Globals.Ribbons.Ribbon1.authStatus.Label = "User Status: Unauthorized";
}
Globals.Ribbons.Ribbon1.PerformLayout(); // Refresh Ribbon to update auth label
}
public static void AppCreation()
{
System.Diagnostics.Debug.WriteLine("AppCreation Start");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
app = PublicClientApplicationBuilder
.Create(clientID)
.WithB2CAuthority($"{AuthorityBase}{SignInPolicy}")
.WithRedirectUri(redirectURI)
.Build();
System.Diagnostics.Debug.WriteLine("AppCreation Finish");
}
private static async Task AuthenticateUser()
{
System.Diagnostics.Debug.WriteLine("AuthenticateUser Start");
// Variables (Pre Authentication)
AuthenticationResult result;
string[] scopes = new string[] { "openid", "offline_access" };
// Retrieve accounts
var accounts = await app.GetAccountsAsync();
try
{
// Silent Authentication
System.Diagnostics.Debug.WriteLine("Try Silent Auth Flow");
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
System.Diagnostics.Debug.WriteLine("Finish Silent Auth Flow");
}
catch (MsalUiRequiredException)
{
try
{
System.Diagnostics.Debug.WriteLine("Try Interactive Auth Flow");
foreach (var account in accounts)
{
System.Diagnostics.Debug.WriteLine("account: " + account.ToString());
}
// Interactive Authentication
result = await app.AcquireTokenInteractive(scopes).WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount).ExecuteAsync();
System.Diagnostics.Debug.WriteLine("Finish Interactive Auth Flow");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Failed Auth");
// Failed Authentication
System.Diagnostics.Debug.WriteLine(ex.ToString());
isAuthorizedUser = false;
return;
}
}
MessageBox.Show("Authenticated");
isAuthorizedUser = true;
return;
}
}
}

Подробнее здесь: https://stackoverflow.com/questions/792 ... el-add-ins