簡體   English   中英

錯誤:沒有帳戶或登錄提示傳遞給 AcquireTokenSilent 調用

[英]Error : No account or login hint was passed to the AcquireTokenSilent call

情況:我使用 blazor 服務器開發了 web 應用程序,該服務器連接到我的 web Z8A5DA52ED120547D3597E。 Web Api use swagger, and I use nswagstudio to generate c# proxy class and interface that i am using in Web App. Web App is secured with azure ad login (Microsoft.Identity) and Web Api is secured by bearer token in http header (also checked agains azure ad). 我正在使用代碼添加 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 時嘗試獲取不記名令牌時,總是出現異常

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 服務時在 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);
                }
            });
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM