使用 Azure Active Directory 作为 Identity Server 的外部登录

Use Azure Active Directory as an external login for Identity Server

我有一个使用 IdentityServer 进行登录的 .NET 6 Web 应用程序。我想扩展该功能并使用 Azure Active Directory (AAD) 作为外部登录。 我的 Program.cs 中有以下代码,它将 AAD 注册为外部提供程序:

builder.Services.AddAuthentication()
        .AddOpenIdConnect("aad", "Sign-in with Azure AD", options =>
        {
            options.Authority = "https://login.microsoftonline.com/common";
            options.ClientId = "<clientID>";
            options.ClientSecret = "<clientSecret>";

            options.SignInScheme = IdentityConstants.ExternalScheme;
            options.SignOutScheme = IdentityServerConstants.SignoutScheme;

            options.ResponseType = "id_token";
            options.CallbackPath = "/signin-aad";
            options.SignedOutCallbackPath = "/signout-callback-aad";
            options.RemoteSignOutPath = "/signout-aad";

            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                NameClaimType = "name",
                RoleClaimType = "role"
            };
        });

我被重定向到 Azure 门户,但在我 select 相应的帐户后,我收到以下错误:

注意:我也使用 IdentityServerConstants.ExternalCookieAuthenticationScheme 而不是 IdentityConstants.ExternalScheme 作为登录方案,结果是一样的。

我已经阅读了很多博客文章并尝试重现在整个互联网上找到的多个解决方案,但我的结果总是一样的(如上所示的异常)。 如果有人有任何其他建议,我可能会尝试解决这个问题,我们将不胜感激任何提示。 谢谢, 祝你有美好的一天!

在一些同事的帮助下,我最终找到了答案。 修复是在 builder.Services.AddAuthentication.

上方添加以下代码块
    builder.Services.Configure<CookiePolicyOptions>(options =>
    {
        options.Secure = CookieSecurePolicy.Always;
    });

另外,修改了以下代码。我已将 SameSiteMode 更改为 None 并添加了 UseCookiePolicy

    app.UseCookiePolicy(new CookiePolicyOptions()
    {
        MinimumSameSitePolicy = SameSiteMode.None
    });

    app.UseCookiePolicy();

希望这对以后可能遇到同样问题的其他人有所帮助。