使用两个应用程序时的 Azure AD 身份验证重定向循环(cookie 错误)

Azure AD authentication redirect loop (cookie error) when using two apps

我有两个受 Azure AD 保护的 asp.net 核心 Web 应用程序(使用相同的应用程序注册 ID)。如果我登录一个,另一个的身份验证流程就会中断,但反过来不会。

我认为它与身份验证 cookie 有关,并且管理应用程序选择了为门户应用程序创建的那个。如果这个假设是正确的,我如何确保应用程序不使用彼此的 cookie?

设置

测试用例

OK : Load Admin and log in
OK : Load Portal and log in
NOK: Load the Portal and log in, navigate to Admin (auth loop)         
NOK: Load Admin and log in,
        navigate to Portal (credentials not requested, reusing the cookie i guess), 
        reload Admin (auth loop)

管理应用程序报告以下错误并创建身份验证重定向循环。 Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:信息:Cookie 未通过身份验证。失败消息:取消保护票失败

Startup.cs 门户应用

public class Startup
{
    public Startup( IConfiguration configuration )
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices( IServiceCollection services )
    {
        services.AddAuthentication( o =>
            {
                o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            }
        ).AddOpenIdConnect( o =>
            {
                o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                o.ClientId = "same-for-both-apps";
                o.CallbackPath = "/portal/signin-oidc";
                o.Authority = "https://login.windows.net/common";
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    RoleClaimType = ClaimTypes.Role,
                    ValidateIssuer = false,
                };
            }
        ).AddCookie( options =>
            { options.AccessDeniedPath = new PathString( "/Account/AccessDenied" ); } );

        services.AddMvc( o =>
            {
                o.Filters.Add( new AuthorizeFilter(
                                    new AuthorizationPolicyBuilder()
                                    .RequireAuthenticatedUser()
                                    .Build() ) );

            }
        ).SetCompatibilityVersion( CompatibilityVersion.Version_2_2 );
    }

    public void Configure( IApplicationBuilder app, IHostingEnvironment env )
    {
        app.MapWhen( IsTargetingPortal, HandlePortalRequest );

        app.Run( async ctx =>
        {
            await ctx.Response.WriteAsync( "Default: info page" );
        } );
    }

    bool IsTargetingPortal( HttpContext ctx )
    {
        return ctx.Request.Path == "/portal/signin-oidc" ||
               ctx.Request.Path == "/portal" ||
               ctx.Request.Host.Host.StartsWith( "portal." );
    }

    void HandlePortalRequest( IApplicationBuilder builder )
    {
        builder.UseAuthentication();
        builder.UseMvc( routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}" );
        } );
    }
}

Startup.cs 用于管理应用

public class Startup
{

    public Startup( IConfiguration configuration )
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices( IServiceCollection services )
    {
        services.AddAuthentication( o =>
            {
                o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            } 
        ).AddOpenIdConnect( o =>
            {
                o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                o.ClientId = "same-for-both-apps";                    
                o.Authority = "https://login.windows.net/common";
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    RoleClaimType = ClaimTypes.Role,
                    ValidateIssuer = false,
                };
            } 
        ).AddCookie( options => 
            { options.AccessDeniedPath = new PathString( "/Account/AccessDenied" ); } );

        services.AddMvc( o =>
            {
                o.Filters.Add( new AuthorizeFilter( 
                                    new AuthorizationPolicyBuilder()
                                    .RequireAuthenticatedUser()
                                    .Build() ) );

            } 
        ).SetCompatibilityVersion( CompatibilityVersion.Version_2_2 );
    }

    public void Configure( IApplicationBuilder app, IHostingEnvironment env )
    {
        app.UsePathBase( "/admin" );

        if( env.IsDevelopment() )
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler( "/Error" );
            app.UseHsts();
        }

        app.UseAuthentication();
        app.UseMvc();
    }
}

这需要在 Azure AD 门户中分别注册这两个应用程序。这将为您提供不同的客户端 ID。为每个应用程序使用不同的客户端 ID。

我通过添加

解决了 cookie 混淆问题
builder.UsePathBase( "/portal" );

到管道的门户分支

private void HandlePortalRequest( IApplicationBuilder builder )
{            
    builder.UsePathBase( "/portal" ); // the fix!

    builder.UseAuthentication();

    builder.UseMvc( routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Portal}/{action=Index}/{id?}" );
    } );
}