WebApi授权拦截——重写AuthorizeAttribute

    跟mvc一样,webapi大多通过附加Authorize特性来实现授权,Authorize当授权失败时返回状态码:401。一般系统状态为401时,服务端就Redirect重定向到登录页。
    问题来了,我们的webapi在为富客户端ajax提供服务时,合理的做法是无论服务端发生什么情况,都尽可能给客户端返回json,才方便ajax回调函数解析。而重定向到登录了,则将返回登录页的一串html,ajax回调函数就傻傻的分不清楚啦。
    当然,解决办法是有的,思路为:重写Authorize的HandleUnauthorizedRequest,让服务端返回json,并且把状态码401改为其他状态码来避免被重定向。最合理的是改为403,表示服务器拒绝。
重写Authorize有以下几个要点需注意:
  1. HandleUnauthorizedRequest中基类方法已经将Response的状态设为”HttpStatusCode.Unauthorized(即401)“,重写时手请动改为”HttpStatusCode.Forbidden(即403)“,否则按401状态往下执行,就要被重定向到登录页;
  2. webApi下的授权筛选attribute为System.Web.Http.AuthorizeAttribute,而Mvc下用的是System.Web.Mvc.AuthorizeAttribute。这里别继承错了,否则授权筛选attrbute拦截不了。
  3. WebApi下Authorize.HandleUnauthorizedRequest的参数filterContext在此上下文里response还为空,需要手动创建。
    
以下是我重写的Authorize:
 1  /// <summary>
 2     /// 重写实现处理授权失败时返回json,避免跳转登录页
 3     /// </summary>
 4     public class ApiAuthorize : AuthorizeAttribute
 5     {
 6         protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
 7         {
 8             base.HandleUnauthorizedRequest(filterContext);
 9 
10             var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
11             response.StatusCode = HttpStatusCode.Forbidden;
12             var content = new Result
13             {
14                 success = false,
15                 errs = new[] { "服务端拒绝访问:你没有权限,或者掉线了" }
16             };
17             response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
18         }
19     }

运行结果:
 
 
chrome下查看返回状态:
 
 
 
Demo已经上传,需要的朋友请点击下载:示例源码
 

posted on 2016-07-27 21:31  wch_99  阅读(26412)  评论(24编辑  收藏  举报

导航