为什么声明转换不会减少 cookie 大小?

2024-01-10

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

Whether I use the claims transformation or not, the cookie size is the same: Cookie Size

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

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

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

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

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 块减少到 2 块。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么声明转换不会减少 cookie 大小? 的相关文章

随机推荐