眾所周知,在Asp.net WebAPI中,認(rèn)證是通過AuthenticationFilter過濾器實現(xiàn)的,我們通常的做法是自定義AuthenticationFilter,實現(xiàn)認(rèn)證邏輯,認(rèn)證通過,繼續(xù)管道處理,認(rèn)證失敗,直接返回認(rèn)證失敗結(jié)果,類似如下:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var principal = await this.AuthenticateAsync(context.Request); if (principal == null) { context.Request.Headers.GetCookies().Clear(); context.ErrorResult = new AuthenticationFailureResult("未授權(quán)請求", context.Request); } else { context.Principal = principal; } }