azure - 使用 Asp .NET Core 的 Multi-Tenancy Web 应用程序登录问题

标签 azure asp.net-core azure-active-directory azure-web-app-service multi-tenant

将应用程序设置为 Multi-Tenancy 后,出现以下错误。一个 处理请求时发生未处理的异常。

SecurityTokenInvalidIssuerException: IDX10205: Issuer validation failed. Issuer: 'https://sts.windows.net/2566cb39-d9fg-5ad6-tryb-d1e2kl067a89/'. Did not match: validationParameters.ValidIssuer: 'null' or validationParameters.ValidIssuers: 'https://sts.windows.net/{tenantid}/'.

Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() Stack Query Cookies Headers SecurityTokenInvalidIssuerException: IDX10205: Issuer validation failed. Issuer: 'https://sts.windows.net/2096cb39-d9fd-4ad6-bbeb-d1e2be067a89/'. Did not match: validationParameters.ValidIssuer: 'null' or validationParameters.ValidIssuers: 'https://sts.windows.net/{tenantid}/'. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext() System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Session.SessionMiddleware+d__9.MoveNext() Microsoft.AspNetCore.Session.SessionMiddleware+d__9.MoveNext() System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

下面是startup.cs代码

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using LPPlusUI.Models;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.FileProviders;
    using Microsoft.IdentityModel.Tokens;
    using ReflectionIT.Mvc.Paging;
    namespace LPPlusUI
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            public IConfiguration Configuration { get; }
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                .AddAzureAd(options => Configuration.Bind("AzureAd", options))
                .AddCookie();
                services.AddDistributedMemoryCache();
                services.AddSession(options => {
                    options.IdleTimeout = TimeSpan.FromMinutes(30);//You can set Time   
                });
                services.AddMvc();
                services.AddPaging();
                var connection = @"string";
                services.AddDbContext<LPPlusExamContext>(options => options.UseSqlServer(connection));
            }
            //This method gets called by the runtime.Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                app.UseStaticFiles();
                app.UseSession();
                app.UseAuthentication();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
            }
        }

以下是 appsettings.json 中的代码

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AzureAd": {
        "ClientId": "141b2123-d239-3568a-a713-4d4fg5781f57",
        "Domain": "lpstaging.onmicrosoft.com",
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "common",
        "CallbackPath": "/signin-oidc",
        "ClientSecret": "eVLSRM7yHjkjh678sghgjdGTh7shjkSgtGSU4=",
        "AppIDURL": "https://lpstaging.onmicrosoft.com/<app-id>",
        "ConfigView": "MVC"
      }
    }

最佳答案

我成功了...

services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; })
                .AddOpenIdConnect(options =>
                {
                    var azureadoptions = new AzureAdOptions(); Configuration.Bind("AzureAd", azureadoptions);
                    options.ClientId = $"{azureadoptions.ClientId}";
                    options.Authority = $"{azureadoptions.Instance}{azureadoptions.TenantId}";
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        ValidAudience = $"{azureadoptions.ClientId}",
                        //ValidAudiences = new List<string> { $"{azureadoptions.ClientId}", $"api://{azureadoptions.ClientId}", $"https://myapp.azurewebsites.net/" },
                        //ValidIssuer = $"https://sts.windows.net/{azureadoptions.ClientId}/" // for "signInAudience": "AzureADMyOrg" or "AzureADMultipleOrgs"
                        //ValidIssuer = $"{azureadoptions.Instance}{azureadoptions.TenantId}" // for "signInAudience": "AzureADandPersonalMicrosoftAccount"
                        //ValidIssuers = new List<string> { $"https://sts.windows.net/{azureadoptions.TenantId}/", $"{azureadoptions.Instance}{azureadoptions.TenantId}/v2.0" }                        
                    };
                    //Log.LogInformation($"the AddJwtBearer options have been configured for ClientId = {azureadoptions.ClientId}");
                })
                .AddCookie();

关于azure - 使用 Asp .NET Core 的 Multi-Tenancy Web 应用程序登录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616457/

相关文章:

azure - Microsoft Graph - 同意后获取管理员详细信息

azure - 如何使用 Microsoft Azure 中的 Multi-Tenancy 应用程序在客户端的 Active Directory 中注册应用程序?

azure-active-directory - 没有足够的权限写入架构扩展

python-3.x - Azure 计算机视觉 API 中从本地存储的图像文件进行手写识别

powershell - VSTS Azure powershell : No default subscription has been designated

c# - 如何访问 ASP.NET Core 服务中的路由数据/值提供程序数据?

.net - 如何使用 IHostingEnvironment

azure - 如何在React Native应用程序与Azure服务器中进行SSL Pinning?

sql-server - Azure data studio不会重新连接到本地托管的数据库

c# - 我只看到项目模板 blazorserver,为什么我看不到项目模板 blazor、blazorhosted、blazorlib、blazorserverside?