欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序如何访问带有Token安全认证的API

程序员文章站 2024-03-19 13:35:16
...

微信小程序访问Token安全验证的API接口

API
//添加一个自定义过滤器
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Security;

namespace Web2
{
    public class ApiSecretFilter : ActionFilterAttribute
    {
        //请求有效性验证
        //合法请求为 带有 时间戳+随机数+数据(get/post)+数字签名(token)
        //数字签名=时间戳+随机数+私钥+数据 进行md5加密后的字符串
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string staffid = "p889aabbc#@";
            string timestamp = string.Empty, nonce = string.Empty, singture = string.Empty;
            //消息头中的关键数据
            if (actionContext.Request.Headers.Contains("timestamp"))
            {
                timestamp = actionContext.Request.Headers.GetValues("timestamp").FirstOrDefault();
            }
            if (actionContext.Request.Headers.Contains("nonce"))
            {
                nonce = actionContext.Request.Headers.GetValues("nonce").FirstOrDefault();
            }
            if (actionContext.Request.Headers.Contains("singture"))
            {
                singture = actionContext.Request.Headers.GetValues("singture").FirstOrDefault();
            }
            if (string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(singture))
            {
                throw new Exception("必要参数缺失");
            }
            //http://localhost:9080/api/values?name=张三&age=18  --> name张三age18

            var method = actionContext.Request.Method.Method;
            IDictionary<string, string> sortedParams = null;
            switch (method.ToUpper())
            {
                case "POST":
                case "DELETE":
                case "PUT":
                    Stream stream = HttpContext.Current.Request.InputStream;
                    StreamReader reader = new StreamReader(stream);
                    sortedParams = new SortedDictionary<string, string>(new JsonSerializer().Deserialize<Dictionary<string, string>>(new JsonTextReader(reader)));
                    break;
                case "GET":
                    IDictionary<string, string> paramters = new Dictionary<string, string>();
                    foreach (string item in HttpContext.Current.Request.QueryString)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            paramters.Add(item, HttpContext.Current.Request.QueryString[item]);
                        }
                    }
                    sortedParams = new SortedDictionary<string, string>(paramters);
                    break;

                default:
                    break;
            }
            var data = string.Empty;//请求参数
            StringBuilder query = new StringBuilder();
            if (sortedParams != null)
            {
                foreach (var sort in sortedParams.OrderBy(o => o.Key))
                {
                    if (!string.IsNullOrEmpty(sort.Key))
                    {
                        query.Append(sort.Key).Append(sort.Value);
                    }
                }
                data = query.ToString().Replace(" ", "");
            }
            //生产签名并和客户端传递的签名对比
            var md5 = FormsAuthentication.HashPasswordForStoringInConfigFile(timestamp + nonce + staffid + data, "MD5").ToLower();

            if (!md5.Equals(singture.ToLower()))
            {
                throw new Exception("无权访问");
            }

        }
    }
}
//找到APP_Start文件下的WebApiConfig类进行添加路由
public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            config.Filters.Add(new ApiSecretFilter());
            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
微信小程序
//创建一个MD5目录 MD5 用来加密信息(网上下载一个MD5.js)
![如图所示](https://img-blog.csdnimg.cn/20190409145605944.png)
//创建一个工具目录 tool
![如图所示](https://img-blog.csdnimg.cn/20190409145645356.png)
//tool.js里面代码段
var mds=require('../MD5/MD5.js')
function GetNonce()
{
  return Math.ceil(Math.random()*1000)
}
//时间戳,APi签名,数据,随机数
function Md5(timestamp,staffid,data,nonce)
{
  let d=dictionaryOrderWithData(data);
  return mds.MD5(timestamp+staffid+d+nonce);
}
function dictionaryOrderWithData(dic)
{
  var result="";
  var sdic=Object.keys(dic).sort(function(a,b){return a.localeCompare(b)});
  var value="";
  for(var ki in sdic)
  {
    if(dic[sdic[ki]]==null)
    {
      value=""
    }
    else
    {
      value=dic[sdic[ki]];
    }
    result+=sdic[ki]+value;
  }
  return result.replace(/\s/g,"");
}
module.exports={
  Nonce:GetNonce,
  MD5:Md5
}
//然后在你请求API的代码段之前
    //时间戳
    let timestamp = Date.parse(new Date());
    //随机数
    let nonce = tool.Nonce().toString();
    //请求数据
    let data = { name: app.globalData.userInfo.nickName, iv: e.detail.iv, encryptedData: e.detail.encryptedData, code: app.globalData.code };
    //API定义的签名
    let staffid = "p889aabbc#@";
    //进行加密
    let md5=tool.MD5(timestamp,staffid,data,nonce);
    wx.request({
    //请求路径
      url: server +'api/LibraryManage/AddWcReader',
      method:"post",
      header:{
        timestamp: timestamp,
        nonce: nonce,
        singture:md5
      },
      data: data,
      success:function(res){
      console.log("请求成功");
      }

上一篇: Spring Security学习笔记-Filter

下一篇: