簡體   English   中英

嘗試通過 azure AD 多租戶用戶驗證我的應用程序時出現以下錯誤

[英]im getting following error when tryng to Authenticate my app through azure AD Multiple tenant users

錯誤:InvalidOperationException:IDX20803:無法從以下位置獲取配置:'['System.String' 類型的 PII 被隱藏。 有關更多詳細信息,請參閱 https://aka.ms/IdentityModel/PII.]'。

i have registered my API and web application both as multitenant but im not able to log in through another tenant,when im accessing the API through the app using the same tenant user in which app and api is registered it is letting me login,but cant與多個租戶一起完成。

when im adding instance as 
"Instance": "https://login.microsoftonline.com",
it is working fine.
but when i add instance as
"Instance": "https://login.microsoftonline.com/common", 
it throws error. 

here is the code i have written inside startup.cs of web application



 public void ConfigureServices(IServiceCollection services)
            {
              
                IdentityModelEventSource.ShowPII = true;
                services.AddHttpClient<ITokenService, TokenService>();
                services.AddMicrosoftIdentityWebAppAuthentication(Configuration).EnableTokenAcquisitionToCallDownstreamApi(new string[]
               { Configuration["APIConfig:APIScope"]}).AddInMemoryTokenCaches();
    
                services.AddControllersWithViews(option =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                    option.Filters.Add(new AuthorizeFilter(policy));
                });
    
                services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        // Instead of using the default validation (validating against a single issuer value, as we do in
                        // line of business apps), we inject our own multitenant validation logic
                        ValidateIssuer = false,
    
                        // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                        //IssuerValidator = (issuer, securityToken, validationParameters) => {
                        //    if (myIssuerValidationLogic(issuer)) return issuer;
                        //}
                    };
    
                    options.Events = new OpenIdConnectEvents
                    {
                        OnTicketReceived = context =>
                        {
                            // If your authentication logic is based on users then add your logic here
                            return Task.CompletedTask;
                        },
                        OnAuthenticationFailed = context =>
                        {
                            context.Response.Redirect("/Error");
                            context.HandleResponse(); // Suppress the exception
                            return Task.CompletedTask;
                        },
                        // If your application needs to authenticate single users, add your user validation below.
                        //OnTokenValidated = context =>
                        //{
                        //    return myUserValidationLogic(context.Ticket.Principal);
                        //}
                    };
                });
    
                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                });
                services.AddRazorPages();
            }
  
    this is the code for aquiring token 
   
     public interface ITokenService
        {
            public Task<string> Get();
        }
        public class TokenService : ITokenService
        {
    
            private readonly HttpClient _httpClient;
            private readonly string _APIScope = string.Empty;
            private readonly string _APIBaseAddress = string.Empty;
            private readonly ITokenAcquisition _tokenAquisition;
    
            public TokenService(ITokenAcquisition tokenAquisition, HttpClient httpClient, IConfiguration configuration)
            {
                _httpClient = httpClient;
                _tokenAquisition = tokenAquisition;
                _APIScope = configuration["APIConfig:APIScope"];
                _APIBaseAddress = configuration["APIConfig:APIBaseaddress"];
            }
          
          
            public async Task<string> Get()
            {
                await FindToken();
                var response = await _httpClient.GetAsync($"{_APIBaseAddress}/weatherforecast");
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var output = JsonConvert.DeserializeObject<string>(content);
                    return output;
                }
                throw new HttpRequestException("Invalid Response");
            }
            private async Task FindToken()
            {
                var accessToken = await _tokenAquisition.GetAccessTokenForUserAsync(new[] { _APIScope });
    
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            }
        }
  • Authority必須類似於"https://login.microsoftonline.com/common" ,它是實例和租戶 ID 的組合。 所以這里的實例必須是https://login.microsoftonline.com

還要檢查這里的評論> IDX20803: Unable to get configuration from

  • 嘗試將 web 應用的最低 TLS 版本從 1.0 更改為 1.2。

  • 在某些情況下,即使在加載元數據之后,包也可能默認為 TLS 1.1。

  • 為了解決這個問題,我在 Global.asax.cs 中添加了以下內容:

     protected void Application_Start() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; // allow TLSV1.2 and SSL3 only //other code }

您可能需要檢查真正的錯誤。正如您所做的那樣IdentityModelEventSource.ShowPII = true; 在 start up.cs 請檢查日志以了解確切的錯誤。

if (env.IsDevelopment())
{
    IdentityModelEventSource.ShowPII = true;
}

暫無
暫無

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

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