API网关Kong系列(四)认证配置

目前根据业务须要先介绍2种认证插件:Key Authentication 及 HMAC-SHA1 认证算法

  Key Authenticationdocker

 

向API添加密钥身份验证(也称为API密钥)。 而后,消费者能够在 querystring 参数或 Header 头中添加其密钥,以验证其请求。服务器


 进入以前部署好的kong-ui,选择plugins,点击+号ui

 

按需求输入参数加密

一样建立一个消费者spa

 其中客户Id为选填插件

生成后进入消费者列表,编辑该用户,按一下操做生成对应的key。代理

同时咱们能够看到消费者中包含有其余插件所需的属性等,能够按需本身生成。code

 

 

 添加后以下blog

 

 

使用起来也很简单,将key(以前添加插件是设置的key名称)插入header值便可

 

若是验证错误则返回403

 

 
  HMAC Authentication

为您的API添加HMAC签名身份验证以创建使用者的身份。 插件将在代理受权和受权Header中检查有效的签名(按此顺序)。 这个插件实现遵循draft-cavage-http-signatures-00草案略有改变的签名方案。

 根据如上方法,同理增长HMAC认证凭证

同理加入HMAC插件

 

 

 HMAC-SHA1,C#代码实现:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Security.Cryptography
{
    public static class HMAC_SHA1
    {
        public static string Sign(string text, string key, string inputCharset = "utf-8")
        {
            Encoding _encode = Encoding.GetEncoding(inputCharset);
            byte[] _byteData = Encoding.GetEncoding(inputCharset).GetBytes(text);
            HMACSHA1 _hmac = new HMACSHA1(_encode.GetBytes(key));

            using (CryptoStream _cs = new CryptoStream(Stream.Null, _hmac, CryptoStreamMode.Write))
            {
                _cs.Write(_byteData, 0, _byteData.Length);
            }
            return Convert.ToBase64String(_hmac.Hash);
        }
    }
}

 

请求的时候主要是header中

Authorization 的构造,根据官方文档

Authorization: hmac username="bob", algorithm="hmac-sha1", headers="date content-md5", signature="Base64(HMAC-SHA1(signing string))"

若是有多个Header的话,header名称用空格隔开,注意官方文档中的"date"现在应该改为"x-date",date的格式请使用GMT时间诸如"Wed, 01 Mar 2017 05:05:24 GMT"

官方文档中加密字符串:

date: Fri, 09 Oct 2015 00:00:00 GMT\ncontent-md5: lCMsW4/JJy9vc6HjbraPzw==

注意也要将date修改为x-date,若是没有content-md5这个头,那就不用加\n,直接为

x-date: Fri, 09 Oct 2015 00:00:00 GMT

 

这边提供一组正确的加密字串,供你们实现算法后验证

secret:secret7496

加密前字符串:x-date: Wed, 01 Mar 2017 05:05:24 GMT

摘要字符串为:XefFQYm8HRXsocJHF4ibDEPWW3k=

 

重要备注:

这个HMAC主要碰到2类错误

1.HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication

这个错误主要2种状况都跟日期有关

  1)服务器时间跟客户端发出去的x-date的间隔时间超过以前定义的clock skew秒数(经过docker容器安装的容易产生这个问题)

  2)请确认是GMT时间格式

  3)把date改为x-date

2.HMAC signature does not match

这个就是签名算法有问题了

相关文章
相关标签/搜索