Web API 授权筛选器

方式一、全局认证

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API 配置和服务
        config.Filters.Add(new ApiAuthorizeAttribute());
    }
}

 

方式二、局部认证

在控制器前加认证特性[ApiAuthorizeAttribute],方法名前加认证特性

[ApiAuthorizeAttribute]
public class ValuesController : ApiController
{
    [Authorize]
    public void Post([FromBody]string value)
    {
    }
}

 以下为自定义授权筛选器文件

/// <summary>
/// 授权筛选器
/// </summary>
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var tokenHeader = from t in actionContext.Request.Headers where t.Key == "token" select t.Value.FirstOrDefault();
        if (tokenHeader != null)
        {
            string token = tokenHeader.FirstOrDefault();
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        return false;
    }

    /// <summary>
    /// 处理授权失败的请求
    /// </summary>
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new
        {
            code = "3001",
            msg = "false",
            data = new { }
        }, "application/json");
    }
}

 

posted @ 2019-10-29 17:57  microsoftzhcn  阅读(638)  评论(0编辑  收藏  举报