概述

事件中心使用在命名空间和事件中心级别提供的共享访问签名。SAS令牌是从SAS密钥生成的,它是以特定格式编码的URL的SHA哈希。 事件中心可以使用密钥(策略)的名称和令牌重新生成哈希,以便对发送者进行身份验证。通常,为事件发布者创建的SAS令牌只对特定的事件中心具有“发送”权限。

说明

目前关于直接使用SAS方式连接Azure EventHub,官方只是给出了原理性的介绍,并未给出具体的使用示例,下面分别使用Java SDK和Rest API演示其使用方法。


Java Sample
pom.xml
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventhubs</artifactId>
<version>1.0.2</version>
</dependency>
Code Sample

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.azure.eventhubs.*; import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService; public class SaSCodeSample { public static void main(String[] args)
throws EventHubException, ExecutionException, InterruptedException, IOException { //Set parameters
final String keyName = "RootManageSharedAccessKey";
final String key = "v47cgE7VHVTnHQUhpWMtRKrrlQEJGVBr42**********";
final String eventhubNamespace = "yueventhub";
final String eventhubName = "yutest";
final String resourceUri = "https://"+eventhubNamespace+".servicebus.chinacloudapi.cn/"+eventhubName; final String sasString = GetSASToken(resourceUri,keyName,key);
final ConnectionStringBuilder connStr = new ConnectionStringBuilder()
.setSharedAccessSignature(sasString)
.setEventHubName(eventhubName)
.setEndpoint(URI.create("sb://"+eventhubNamespace+".servicebus.chinacloudapi.cn")); final Gson gson = new GsonBuilder().create();
final ExecutorService executorService = Executors.newSingleThreadExecutor(); //Create EventHub Client
final EventHubClient ehClient = EventHubClient.createSync(connStr.toString(), executorService); //Send messages to EventHub final int messageOfAccount = 10;
try {
for (int i = 0; i < messageOfAccount; i++) { String payload = "Message " + Integer.toString(i);
byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
EventData sendEvent = EventData.create(payloadBytes);
System.out.println("i : "+ i);
ehClient.sendSync(sendEvent);
} System.out.println(Instant.now() + ": Send Complete...");
System.in.read();
} finally {
ehClient.closeSync();
executorService.shutdown();
}
} //Create SharedAccessSignature
private static String GetSASToken(String resourceUri, String keyName, String key)
{
long epoch = System.currentTimeMillis()/1000L;
int week = 60*60*24*7;
String expiry = Long.toString(epoch + week); String sasToken = null;
try {
String stringToSign = URLEncoder.encode(resourceUri, "UTF-8") + "\n" + expiry;
String signature = getHMAC256(key, stringToSign);
sasToken = "SharedAccessSignature sr=" + URLEncoder.encode(resourceUri, "UTF-8") +"&sig=" +
URLEncoder.encode(signature, "UTF-8") + "&se=" + expiry + "&skn=" + keyName;
} catch (UnsupportedEncodingException e) { e.printStackTrace();
}
return sasToken;
} public static String getHMAC256(String key, String input) {
Mac sha256_HMAC = null;
String hash = null;
try {
sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
Base64.Encoder encoder = Base64.getEncoder(); hash = new String(encoder.encode(sha256_HMAC.doFinal(input.getBytes("UTF-8")))); } catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return hash;
}
}
Postman Test(使用工具生成JS Code)

var request = require("request"); var options = { method: 'POST',
url: 'https://yueventhub.servicebus.chinacloudapi.cn/yutest/messages',
headers:
{ 'postman-token': 'df23522a-5cf9-7756-5442-de8387557f6f',
'cache-control': 'no-cache',
authorization: 'SharedAccessSignature sr=https%3A%2F%2Fyueventhub.servicebus.chinacloudapi.cn%2Fyutest&sig=3c39JXnSD3k2xktNKzRD/d6cBY%2BVg08a**********g%3D&se=1535965635&skn=RootManageSharedAccessKey',
'content-type': 'text/plain' },
body: '{ “Location”: “Redmond”, "Temperature":"37.0" }' }; request(options, function (error, response, body) {
if (error) throw new Error(error); console.log(body);
});

参考

Event Hubs service REST

Generate SAS token

azure-event-hubs-java

使用SAS令牌连接Azure EventHub的更多相关文章

  1. 使用PowerShell 连接Azure

    除了使用门户登入外,还可以使用PowerShell的方式来连接Azure.首先要去下载组件 http://azure.microsoft.com/en-us/downloads/?rnd=1 http ...

  2. 本地git部署web连接azure的git存储库

    ​​​本地git部署web 创建本地存储仓库 输入以下命令创建git本地仓库(会在当前目录下生产一个.git的目录) git init 然后提交内容 在git仓库所在的目录下存放好需要的网页文件 将文 ...

  3. PHP连接Azure Redis

    概述 Azure Redis缓存基于流行的开源Redis缓存,可以通过各种Redis客户端进行访问,这些客户端适用于许多编程语言.每个客户端有自身的API,用于通过Redis命令调用Redis缓存实例 ...

  4. pymssql连接Azure SQL Database

    使用pymssql访问Azure SQL Database时遇到"DB-Lib error message 20002, severity 9:\nAdaptive Server conne ...

  5. 使用PuTTY连接Azure VM

    使用PuTTY连接Azure VMhtml { -webkit-print-color-adjust: exact } * { box-sizing: border-box; -webkit-prin ...

  6. 【Azure Redis 缓存】 Python连接Azure Redis, 使用redis.ConnectionPool 出现 "ConnectionResetError: [Errno 104] Connection reset by peer"

    问题描述 Python连接Azure Redis, 使用redis.ConnectionPool 出现 "ConnectionResetError: [Errno 104] Connecti ...

  7. Java连接Azure SQL Database

    Azure SQL Database是Azure上的数据库PAAS服务,让用户可以快速的创建和使用SQL数据库而不用担心底层的备份,安全,运维,恢复等繁琐的工作,本文简单介绍如何使用Java程序连接到 ...

  8. 手把手:使用service principal连接Azure Media Service

    在简书中查看,请点击我. 关于相关内容解释,请参考docs文档 https://docs.microsoft.com/en-us/azure/media-services/previous/media ...

  9. .net core 实践笔记(二)--EF连接Azure Sql

    ** 温馨提示:如需转载本文,请注明内容出处.** 本文链接:https://www.cnblogs.com/grom/p/9902098.html 笔者使用了常见的三层架构,Api展示层注入了Swa ...

随机推荐

  1. Undefined index: validate(thinkphp)

    今天在用thinkphp3.23时发现错误 NOTIC: [8] Undefined index: validate  此处是thinkphp核心目录\Think\Model.class.php 第 ...

  2. Unity防破解 —— 重新编译mono

        Unity4.x版本导出android包时,只能选择mono,无法使用il2cpp,这就造成了我们的程序集很容易被修改--很多朋友在发布项目时觉得即使代码暴露出去也没什么关系,只有项目火了才有 ...

  3. 软件工程中的反面模式(anti-pattern)

    软件设计 抽象倒置(Abstraction inversion):不把用户需要的功能直接提供出来,导致他们要用更上层的函数来重复实现 用意不明(Ambiguous viewpoint):给出一个模型( ...

  4. 分析器错误 未能加载类型“XX.WebApiApplication”

    解决方案,删除bin目录下内容(有单独使用dll的删除前请先备份) 清理解决方案并重新生成

  5. 大湿教我写程序(2)之走向AV之路

    一.大摆庆功宴 上一篇博文<大湿教我写程序(1)之菜单导航篇>中讲到了我撸码到晚上两点多,整出了一个还算是高端大气上档次的demo.半夜回到家里打算着可以好好睡上一个懒觉,到时候直接到客户 ...

  6. 【json】前台ajax序列化的多个属性拼接在一起的字符串,转化为JSONObject对象

    1.首先看一下前台序列化了哪些东西: 部分js代码 //查询按钮 $(".questButton").click(function(){ $.ajax({url:"/qu ...

  7. [Git] Git 的origin和master分析

    转载: http://lishicongli.blog.163.com/blog/static/1468259020132125247302/ 首先要明确一点,对git的操作是围绕3个大的步骤来展开的 ...

  8. Shell实现多级菜单系统安装维护脚本实例分享

    Shell实现多级菜单系统安装维护脚本实例分享 这篇文章主要介绍了Shell实现多级菜单系统安装维护脚本实例分享,本文脚本用多级菜单实现管理WEB服务器.Mysql服务器.Nginx服器等,需要的朋友 ...

  9. Kubernetes用户指南(二)--部署组合型的应用、连接应用到网络中

    一.部署组合型的应用 1.使用配置文件启动replicas集合 k8s通过Replication Controller来创建和管理各个不同的重复容器集合(实际上是重复的pods). Replicati ...

  10. Kubernetes用户指南(一)--快速开始、使用k8s配置文件

    一.快速开始 1.启动一个简单的容器. 一旦在container中打包好应用并将其commit为image之后,你就可以将其部署在k8s集群上. 一个简单的nginx服务器例子: 先决条件:你需要拥有 ...