У меня есть следующая функция для вызова пользователей из активного каталога, используя graph api. Эта функция нажата при каждом нажатии на текстовое поле. Но я получаю следующую ошибку
Код: TokenNotFound Сообщение: пользователь не найден в кэше токена. Возможно, сервер был перезапущен.
в этой строке кода
var user = await graphClient.Users.Request().GetAsync();
Мой класс
public class GraphSdkHelper : IGraphSdkHelper
{
private readonly IGraphAuthProvider _authProvider;
private GraphServiceClient _graphClient;
public GraphSdkHelper(IGraphAuthProvider authProvider)
{
_authProvider = authProvider;
}
// Get an authenticated Microsoft Graph Service client.
public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
{
_graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Get user's id for token cache.
var identifier = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;
// Passing tenant ID to the sample auth provider to use as a cache key
var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);
// Append the access token to the request
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
}));
return _graphClient;
}
}
public interface IGraphSdkHelper
{
GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity);
}
}
Класс запуска
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public const string ObjectIdentifierType = "http://schemas.microsoft.com/identity/claims/objectidentifier";
public const string TenantIdType = "http://schemas.microsoft.com/identity/claims/tenantid";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddAzureAd(options => Configuration.Bind("AzureAd", options)).AddCookie();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Add application services.
//services.AddSingleton<IConfiguration>(Configuration);
services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>();
services.AddTransient<IGraphSdkHelper, GraphSdkHelper>();
//Connection string
services.AddDbContext<PFEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PFEContext")));
//Group authorization
services.AddAuthorization(options => options.AddPolicy("Customer", policyBuider =>
policyBuider.RequireClaim("groups", "fb721f47-a58c-450a-9fbd-ff13f5960049")));
services.AddAuthorization(options => options.AddPolicy("Developper", policyBuider =>
policyBuider.RequireClaim("groups", "4fad5c4d-9bf9-477b-8814-02dffea5f102")));
services.AddAuthorization(options => options.AddPolicy("ProjectManager", policyBuider =>
policyBuider.RequireClaim("groups", "635b3fff-bb39-4726-8d76-1fef66fb2e8c")));
services.AddAuthorization(options => options.AddPolicy("Tester", policyBuider =>
policyBuider.RequireClaim("groups", "484d8c6c-f458-422f-9e0a-66a971874f3c")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Мне нужно Это же поможет решить эту проблему, что не так?