gpt4 book ai didi

c# - 在 HttpAuthenticationContext 中为 IAuthenticationFilter 设置 Cookie 值

转载 作者:行者123 更新时间:2023-11-30 16:08:23 29 4
gpt4 key购买 nike

我需要在 WebAPI 管道的身份验证步骤中读取/写入 cookie。我为此创建了一个自定义过滤器。

为了遵守自托管概念,访问 cookie 并将其写入客户端的安全方式是什么? Rick Strahl评论说如果我们使用 HttpContext.Current.Response.Cookies.Add(),并且我的应用程序是自托管的,上下文可能/将不存在。

那么我如何使用 HttpAuthenticationContext 将 cookie 写到客户端并且仍然是自托管安全的?

最佳答案

您无法从 IAuthenticationFilter.AuthenticateAsync() 中访问 authContext.ActionContext.Response。好吧,实际上你可以,但只是为了设置一个新的响应并缩短管道的其余部分。

我遇到了同样的问题(需要在成功验证后设置 cookie)并通过实现 IActionFilter 以及 IAuthenticationFilter 解决了这个问题:

async Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
// Process the request pipeline and get the response (this causes the action to be executed)
HttpResponseMessage response = await continuation();

// Here you get access to:
// - The request (actionContext.Request)
// - The response (response) and its cookies (response.Headers.AddCookies())
// - The principal (actionContext.ControllerContext.RequestContext.Principal)

return response;
}

参见:Set cookie from Web Api 2 IAuthenticationFilter AuthenticateAsync method

关于c# - 在 HttpAuthenticationContext 中为 IAuthenticationFilter 设置 Cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com