接口安全认证

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Caching;
using System.Text.RegularExpressions;

namespace WechatServ.Controllers
{
    public class CacheManager
    {
        public static ObjectCache Cache
        {
            get
            {
                return MemoryCache.Default;
            }
        }

        public static bool Contains(string key)
        {
            return Cache.Contains(key);
        }

        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">The key of the value to get.</param>
        /// <returns>The value associated with the specified key.</returns>
        public static T Get<T>(string key)
        {
            return (T)Cache[key];
        }

        /// <summary>
        /// Adds the specified key and object to the cache.
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="data">Data</param>
        /// <param name="cacheTime">Cache time</param>
        public static void Set(string key, object data, int cacheTime)
        {
            if (data == null)
                return;

            var policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
            Cache.Set(new CacheItem(key, data), policy);
        }/// <summary>
        /// Gets a value indicating whether the value associated with the specified key is cached
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>Result</returns>
        public static bool IsSet(string key)
        {
            return (Cache.Contains(key));
        }

        /// <summary>
        /// Removes the value with the specified key from the cache
        /// </summary>
        /// <param name="key">/key</param>
        public static void Remove(string key)
        {
            Cache.Remove(key);
        }

        /// <summary>
        /// Removes items by pattern
        /// </summary>
        /// <param name="pattern">pattern</param>
        public static void RemoveByPattern(string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = new List<String>();

            foreach (var item in Cache)
                if (regex.IsMatch(item.Key))
                    keysToRemove.Add(item.Key);

            foreach (string key in keysToRemove)
            {
                Remove(key);
            }
        }

        /// <summary>
        /// Clear all cache data
        /// </summary>
        public static void Clear()
        {
            foreach (var item in Cache)
                Remove(item.Key);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Web.Http;
using Newtonsoft.Json.Linq;

namespace WechatServ.Controllers
{
    [RoutePrefix("api/Gettokenservice")]
    public class AuthenticationController : ApiController
    {
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost, Route("gettoken")]
        public JObject GetToken([FromBody] JObject data)
        {
            string key = data["key"].ToString();
           JObject result = new JObject();
            result["Code"] = "-2";
            result["Msg"] = "key不存在!";
            result["Token"] = string.Empty;
            if (!string.IsNullOrEmpty(key.ToString()))
            {
                //验证key是否存在
                bool flag = false;
                string keys = System.Configuration.ConfigurationManager.AppSettings["allowKeys"];
                foreach(var s in keys.Split(','))
                {
                    if(s==key)
                    {
                        flag = true;
                    }
                }
                
                //using (IDbConnection con = DBProvider.GetSqlConnection())
                //{
                //    con.Open();
                //    var user = con.Query("select * from [Company] where AbbreviationName=@shortName and Appkey=@key", new { shortName = shortName, key = key });
                //    //var user = con.Query("select * from api_developers ");
                //    if (user != null && user.ToList().Count > 0)
                //    {
                //        flag = true;
                //    }
                //    else
                //    {
                //        result["Msg"] = "企业和appkey不存在";
                //        LogManager.ErrorLog(result["Msg"].ToString());
                //    }
                //    con.Close();
                //}
                if (flag)
                {
                    result["Code"] = "0";
                    result["Msg"] = "success!";
                    result["Token"] = GetMD5(key.ToString()+DateTime.Now.ToString("yyyyMMddHHmmss"));
                    //写入缓存
                    CacheManager.Set(key.ToString(), result["Token"].ToString(), 120);
                }
            }
            else
            {
                result["Msg"] = "key不存在!";
               // LogManager.ErrorLog(result["Msg"].ToString());
            }
            return result;
        }


        ///C#生成MD5的方法
        public static string GetMD5(string sDataIn)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
            }
            return sTemp.ToLower();
        }



    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.IO;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Data.SqlClient;

namespace WechatServ.Controllers
{
    public class OAuthFilter : ActionFilterAttribute
    {
        /// <summary>
        /// OnActionExecuting是Action运行前的操作
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(HttpActionContext context)
        { 
            string msg=string.Empty;

            var key = HttpContext.Current.Request.Headers["key"] ?? "";
            var old_token = HttpContext.Current.Request.Headers["token"] ?? "";
            //var data = (JObject) context.ActionArguments["data"]; //context.Request.Properties["key"].ToString();
            //var key =data["key"]!=null? data["key"].ToString():"";
            //var old_token =data["token"]!=null? data["token"].ToString():"";// context.ActionArguments["token"].ToString();
            //判断token是否存在
            string token = CacheManager.Get<string>(key);
            if (string.IsNullOrEmpty(token) || token != old_token)
            {
                msg="错误的token!";
               // LogManager.ErrorLog("key:" + key + "|token:" + token + "|msg:" + msg);
                context.Response = new HttpResponseMessage(HttpStatusCode.OK);
                context.Response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { code = -1, msg = msg }));  
            }
        }
    }

    public class OAuthOrderFilter :ActionFilterAttribute
    {
        /// <summary>
        /// OnActionExecuting是Action运行前的操作
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(HttpActionContext context)
        {
            var data = (JObject)context.ActionArguments["data"]; //context.Request.Properties["key"].ToString();
            var key = data["key"].ToString();
            var old_token = data["token"].ToString();// context.ActionArguments["token"].ToString();
            string companyKeys = System.Configuration.ConfigurationManager.AppSettings["OrderApiCompanyKeys"].ToString();
            bool flag = false;
            foreach (var k in companyKeys.Split(','))
            {
                if (key == k)
                {
                    flag = true;
                }
            }
            if (flag)
            {
                //判断token是否存在
                string token = CacheManager.Get<string>(key);
                if (string.IsNullOrEmpty(token) || token != old_token)
                {
                    context.Response = new HttpResponseMessage(HttpStatusCode.OK);
                    context.Response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { code = -1, msg = "错误的token!" }));
                }
            }
            else
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.OK);
                context.Response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { code = -1, msg = "此key不允许访问!" }));
            }
            
        }
    }
}
原文地址:https://www.cnblogs.com/d0975/p/14620638.html