gpt4 book ai didi

c# - 错误: No account or login hint was passed to the AcquireTokenSilent call

转载 作者:行者123 更新时间:2023-12-02 02:47:41 24 4
gpt4 key购买 nike

情况:我使用连接到我的 Web API 的 blazor 服务器开发了 Web 应用程序。 Web Api 使用 swagger,我使用 nswagstudio 生成我在 Web 应用程序中使用的 C# 代理类和接口(interface)。Web 应用程序通过 azure 广告登录 (Microsoft.Identity) 进行保护,Web Api 通过 http header 中的不记名 token 进行保护(也再次检查 azure 广告)。我使用代码添加 WebApi 生成的代理:

我注册api代理的扩展方法:

public static void AddMyProxy(this IServiceCollection services)
{
var uri = new MyProxySettings().ApiUrl;

services.AddHttpClient<IMyServiceClient, MyServiceClient>(config =>
{
string token = "";
var serviceProvider = services.BuildServiceProvider();
var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
if (httpContextAccessor?.HttpContext?.User?.Identity?.IsAuthenticated ?? false)
{
var tokenService = serviceProvider.GetService<ITokenAcquisition>();
try
{
token = tokenService.GetAccessTokenForUserAsync(new[] { @"api://xxxxx-yyy-aa-bb-cc/my_scope" }).Result;
}
catch (System.Exception ex)
{
logger.LogError(ex, "error while loading token for current user, try to login again");
}
}

config.BaseAddress = uri;
if (!string.IsNullOrWhiteSpace(token))
{
config.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
});
}

在 WebApp ConfigureServices 方法中:

services.AddSignIn(Configuration, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true);
services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { @"api://xxxxx-yyy-aa-bb-cc/my_scope" })
.AddInMemoryTokenCaches();
services.AddMyProxy();

当我在初始化 DI 时尝试获取不记名 token 时,我总是遇到异常

No account or login hint was passed to the AcquireTokenSilent call

但我尝试在 blazor 页面中执行几乎相同的操作,它适用于 http200 并且 api 返回数据没有任何问题

@code{ 
private string token {get;set;}
private List<MyDto> data {get;set;}

protected async override Task OnInitializedAsync()
{
try

{
token = await tokenService.GetAccessTokenForUserAsync(new string[] { @"api://xxxxx-yyy-aa-bb-cc/my_scope" });
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(@"https://localhost:44365/");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
IMyServiceClient client = new MyServiceClient(httpClient);
var data = await client.ApiV1SomeMethodAsync();
}
catch(Exception e)
{
throw;
}
}
}

那么当我注册 DI 服务时,如何注册我的代理并获取 token 以在 api 调用中使用它?或者我应该尝试其他方法吗?

感谢您的回复和帮助。

最佳答案

问题是从服务集合中提取 ITokenAcquisition 服务。当我使用 httpContextAccessor.HttpContext.RequestServices.GetRequiredService 时,它​​工作正常。

public static void AddMyProxy(this IServiceCollection services)
{
var settings = new MyProxySettings();
var uri = settings.ApiUrl;
var scope = settings.Scope;
services.AddHttpClient<IMyServiceClient, MyServiceClient>(async config =>
{
string token = "";
var serviceProvider = services.BuildServiceProvider();
var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
if (httpContextAccessor?.HttpContext?.User?.Identity?.IsAuthenticated ?? false)
{
**var tokenService = httpContextAccessor.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();**
try
{
token = await tokenService.GetAccessTokenForUserAsync(new[] { scope });
}
catch (System.Exception ex)
{
//logger.LogError(ex, "error while loading token for current user, try to login again");
}
}

config.BaseAddress = uri;
if (!string.IsNullOrWhiteSpace(token))
{
config.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
});
}

关于c# - 错误: No account or login hint was passed to the AcquireTokenSilent call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62518766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com