使用Web Api 2.2,我有一个自定义IAuthenticationFilter
,用于通过自定义方案验证客户端请求。
基本上,当客户端未经过身份验证并想要访问受保护资源时,他会在请求旁边发送Authorization
标头:Authorization: MyCustomScheme XXXXXXX
。然后,过滤器验证凭据,对用户进行身份验证并生成无状态身份验证令牌以进一步访问(类似于JWT)。
我想将生成的身份验证令牌存储在cookie中。当存在于传入请求中时,cookie将在单独的过滤器中进行本地验证(此处未显示)。
我的问题是,如果我尝试像这样设置cookie:
Task IAuthenticationFilter.AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
if (context.Request.Headers.Authorization != null &&
string.Equals(context.Request.Headers.Authorization.Scheme, "MyCustomScheme", StringComparison.OrdinalIgnoreCase))
{
// This works
CustomPrincipal principal = this.ValidateCredentials(context.Request.Headers.Authorization.Parameter);
context.Principal = principal;
// This doesn't work: context.ActionContext.Response is null
var cookie = new CookieHeaderValue("MySessionCookie", principal.AuthenticationToken) { Path = "/", HttpOnly = true };
context.ActionContext.Response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
}
return Task.FromResult(0);
}
然后它失败,因为context.ActionContext.Response
为空。如何在AuthenticateAsync
内的响应中添加Cookie?
参见相关内容:Setting Cookie values in HttpAuthenticationContext for IAuthenticationFilter (你可以在评论中看到人们遇到同样的问题)。
答案 0 :(得分:1)
除了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();
// If the user is authenticated and the token is not present in the request cookies, then it needs to be set
CustomPrincipal principal = actionContext.ControllerContext.RequestContext.Principal as CustomPrincipal;
if (principal != null && !actionContext.Request.Headers.GetCookies("MySessionCookie").Any())
{
// Set the cookie in the response
var cookie = new CookieHeaderValue("MySessionCookie", principal.AuthenticationToken) { Path = "/", HttpOnly = true };
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
}
return response;
}
我觉得这个方法非常不实用(混合接口),你绝对应该可以访问IAuthenticationFilter.AuthenticateAsync
中的响应(通过例如异步延续回调,或者能够访问动作结果{{1在上下文中,就像在同一个接口的IHttpActionResult
方法中一样)。
答案 1 :(得分:1)
我的要求是添加标题,但应该很容易适应添加Cookie。
我对此采取了不同的方法。我把我要添加的标题添加到context.Request.Properties
中。然后在ChallengeAsync
中(无论是否为每个请求调用),通过IHttpActionResult
我检查是否存在属性,如果存在则将其添加到标题中。像这样:
protected class AddRenewOnAauthorizedResult : IHttpActionResult {
public const string RenewalPropertyKey = "ETicket.RenewalKey";
public AddRenewOnAauthorizedResult(HttpRequestMessage request, IHttpActionResult innerResult) {
this.Request = request;
this.InnerResult = innerResult;
}
public HttpRequestMessage Request { get; set; }
public IHttpActionResult InnerResult { get; set; }
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
HttpResponseMessage response = await this.InnerResult.ExecuteAsync(cancellationToken);
if (Request.Properties.ContainsKey(RenewalPropertyKey)) Request.response.Headers.Add("X-ETicket-Renew", Request.Properties(RenewalPropertyKey));
Return response;
}
}
然后在ChallengeAsync
:
public Threading.Tasks.Task ChallengeAsync(HttpAuthenticationChallengeContext context, Threading.CancellationToken cancellationToken)
{
context.Result = new AddRenewOnAauthorizedResult(context.Request, context.Result);
return Task.FromResult(0);
}
答案 2 :(得分:0)
您可能需要实施IRequiresSessionState才能使Cookie保持不变?
请参阅:http://www.strathweb.com/2012/11/adding-session-support-to-asp-net-web-api/