概述

事件中心使用在命名空间和事件中心级别提供的共享访问签名。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. Python timedelta模块 时间增减用法

    timedalte 是datetime中的一个对象,该对象表示两个时间的差值 构造函数:datetime.timedelta(days=0, seconds=0, microseconds=0, mi ...

  2. 关于 hibernate 中 hashCode爆栈的探讨

    今天在 hibernate 的一对多映射测试 merge 方法时,出现了以下的异常: 我们可以看到,这里的错误有非常明显的重复性,很显然是做了间接递归,并且递归的调用是 hashMap 中的hashC ...

  3. Maven学习笔记1

    Maven是什么? 百度百科:Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. 这些描述总是让人更加难理解Maven,扔掉它,咱们先看看Mave ...

  4. DNS无响应

    无语,运行某某大品牌的杀毒软件后,无法上网,window检查后是DNS服务器无响应. 开始>运行>输入"netsh winsock reset"  然后重启电脑. pi ...

  5. luogu P1186 玛丽卡

    题目描述 麦克找了个新女朋友,玛丽卡对他非常恼火并伺机报复. 因为她和他们不住在同一个城市,因此她开始准备她的长途旅行. 在这个国家中每两个城市之间最多只有一条路相通,并且我们知道从一个城市到另一个城 ...

  6. 【动态规划】bzoj1638 [Usaco2007 Mar]Cow Traffic 奶牛交通

    设f[u]为从度数0到u的路径条数,f2[u]为从u到n的路径条数. ans=max{f[x[i]]*f2[y[i]]}(1<=i<=m). #include<cstdio> ...

  7. python基础-函数之装饰器、迭代器与生成器

    1. 函数嵌套 1.1 函数嵌套调用 函数的嵌套调用:在调用一个函数的过程中,又调用了其他函数 def bar(): print("from in the bar.") def f ...

  8. Scala零基础教学【41-60】

    第41讲:List继承体系实现内幕和方法操作源码揭秘 def main(args: Array[String]) { /** * List继承体系实现内幕和方法操作源码揭秘 * * List本身是一个 ...

  9. Java二进制指令代码解析

    http://www.blogjava.net/DLevin/archive/2011/09/13/358497.html http://blog.csdn.net/sum_rain/article/ ...

  10. winfrom GDI知识

     c#使用GDI+简单绘图 http://blog.csdn.net/smartsmile2012/article/details/30255303 NET3.5 GDI+ 图形操作1 http:// ...