asp.net-core - 为什么声明转换不会减少 cookie 大小?

标签 asp.net-core azure-active-directory

我正在使用 Azure AD (.net core 2.1),并已注册我的应用程序并将其配置为返回 AD 组作为声明。我还使用声明转换来删除除我的应用程序使用的三个组之外的所有组声明,这成功地消除了 100 多个组。我这样做是希望能够减少后续请求 header 中 cookie 的大小,但事实似乎并非如此。

无论我是否使用声明转换,cookie 大小都是相同的: Cookie Size

我知道声明转换正在工作,因为我有一个简单的页面,可以迭代列表中的声明,并且当我设置过滤器时,它仅正确显示三个组。

由于 cookie 较大,我收到 HTTP 400 - 请求太长。我可以通过修改 Web 服务器上的注册表来解决这个问题(如其他地方建议的 https://support.microsoft.com/en-us/help/2020943/http-400-bad-request-request-header-too-long-response-to-http-request ),但我真正的问题是,如果 cookie 的大小保持不变,过滤声明的意义何在?

我还想知道是否有一个应用程序设置可以用来增加最大 header 大小,以避免修改注册表。

我不确定代码是否真的与这里相关,但这里有一些片段:

public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
        var identity = principal.Identity as ClaimsIdentity;
        if (identity != null)
        {
            var unused = identity.FindAll(GroupsToRemove).ToList();
            unused.ForEach(c => identity.TryRemoveClaim(c));
        }
        return Task.FromResult(principal);
}

过滤器在 Startup.cs 中注册为单例:

services.AddSingleton<IClaimsTransformation, FilterGroupClaimsTransformation>();

最佳答案

Brad 回答了为什么 cookie 大小没有使用声明转换改变的问题。这是我用来减小 cookie 大小的代码,感谢他的建议:

在 Startup.cs 中,ConfigureServices()...

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(...)
       .AddCookie(options => options.Events.OnSigningIn = FilterGroupClaims);
}

private static Task<ClaimsPrincipal> FilterGroupClaims(CookieSigningInContext context)
{
    var principal = context.Principal;
    if (principal.Identity is ClaimsIdentity identity)
    {
        var unused = identity.FindAll(GroupsToRemove).ToList();
        unused.ForEach(c => identity.TryRemoveClaim(c));
    }
    return Task.FromResult(principal);
}

private static bool GroupsToRemove(Claim claim)
{
    string[] _groupObjectIds = new string[] { };    // pull from config or whereever
    return claim.Type == "groups" && !_groupObjectIds.Contains(claim.Value);
}

对于我的最终解决方案,我将静态方法移到另一个类中,但为了简洁起见,我将所有内容都保留在此处。 使用此方法,Cookie 大小从 6 block 减少到 2 block 。

关于asp.net-core - 为什么声明转换不会减少 cookie 大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314443/

相关文章:

asp.net-core - 使用 OpenIddict 的授权代码流程和 PKCE 示例

asp.net-core - 如何让 GitVersion/UpdateAssemblyInfo 与 ASP.NET Core 2.0 项目一起使用

c# - 为什么我应该只在开发环境中使用用户 secret ?

c# - 如何将计算值添加到此 TryUpdateModelAsync<>

azure - 将 Visual Studio Professional 订阅添加到 Azure 帐户

azure - Get-AzureADUser [-Filter <String>] 命令示例

c# - 在 ASP.NET Core 的中间件中注入(inject)服务

Azure DevOps 和 Azure Active Directory

azure - 如何使用 Microsoft Graph 在 Azure Active Directory 中添加 B2B 用户?

azure - 错误 401 : "Server failed to authenticate the request" while accesing data from Azure Synapse to ADLS Gens