Web API 实战之 授权验证

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Properties;

namespace Ahoo.Demo.WebAPI.Filter
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AuthTokenAttribute : AuthorizationFilterAttribute
    {
        /// <summary>
        /// 验证Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private bool CheckToken(String token)
        {
            return true;
        }

        protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Token已过期!");
        }
        protected virtual bool IsAuthorized(HttpActionContext actionContext)
        {

            KeyValuePair<String, String> obj_Token = actionContext.Request.GetQueryNameValuePairs().FirstOrDefault(m => m.Key.ToLower() == "token");

            if (String.IsNullOrEmpty(obj_Token.Key))
            {
                throw new ArgumentNullException("token");
            }

            return CheckToken(obj_Token.Value);

        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            if (!SkipAuthorization(actionContext) && !IsAuthorized(actionContext))
            {
                HandleUnauthorizedRequest(actionContext);
            }
        }

        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            if (!actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>())
            {
                return actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>();
            }
            return true;
        }

    }
}

你可能感兴趣的:(webapi,授权)