当令牌过期时,有没有更改状态代码和正文以显示其他内容的方法,而不是状态:400的常规响应和“错误”的正文消息:“invalid_client”?
目前,我已设法对标题执行以下操作:
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(context.Token, out ticket))
{
if (ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value.LocalDateTime < DateTime.Now)
{
context.Response.Headers.Add("Expired", new string[] { "Yes" });
}
context.SetTicket(ticket);
}
}
有人帮忙吗?
感谢。
答案 0 :(得分:1)
您可以实现自定义ASP.NET WebApi DelegatingHandler(如果您希望对所有请求进行验证)或ActionFilter(如果您希望针对特定请求/每个端点进行验证) )检查令牌是否仍然有效并中断请求以返回更有意义的响应。有关详细信息,请参阅链接。
我已经实现了一个简单的参考:
public class CustomTokenCheckMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (HasMyTokenExpired())
{
return new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.Unauthorized,
ReasonPhrase = "",
Content = new StringContent("Test") // See HttpContent for more https://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.118).aspx
};
}
return await base.SendAsync(request, cancellationToken);
}
public bool HasMyTokenExpired()
{
//Your custom logic here
return true;
}
}
然后你需要在WebApiConfig文件中注册它,如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
/*
All other config goes here
*/
//This line registers the handler
config.MessageHandlers.Add(new CustomTokenCheckMessageHandler());
}
}