概述

事件中心使用在命名空间和事件中心级别提供的共享访问签名。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. [ubuntu] service apache2 restart [fail]

    $ /etc/init.d/apache2 restart * Restarting web server apache2 [fail] 解决办法4步走: 1. sudo /etc/init.d/ap ...

  2. CF 1006C Three Parts of the Array【双指针/前缀和/后缀和/二分】

    You are given an array d1,d2,-,dn consisting of n integer numbers. Your task is to split this array ...

  3. LCIS最长公共上升子序列

    最长公共上升子序列LCIS,如字面意思,就是在对于两个数列A和B的最长的单调递增的公共子序列. 这道题目是LCS和LIS的综合. 在LIS中,我们通过两重循环枚举当序列以当前位置为结尾时,A序列中当前 ...

  4. hdu6070

    hdu6070 题意 给出 \(n\) 个数, \(\frac{x}{y}\) 表示某个区间不同数的个数除以区间的长度,求 \(\frac{x}{y}\) 最小值. 分析 设 \(size(l, r) ...

  5. [姿势]cpp - memset

    头文件:memory.h 可以刷的有: memset(array,,sizeof(array)); //全部赋0 memset(array,-,sizeof(array)); //全部赋-1 用法和用 ...

  6. [BZOJ3786]星系探索(伪ETT)

    3786: 星系探索 Time Limit: 40 Sec  Memory Limit: 256 MBSubmit: 1638  Solved: 506[Submit][Status][Discuss ...

  7. [CF441E]Valera and Number

    题意:给定$x,k,p$和一份伪代码,伪代码大致是循环$k$次,每次有$p\%$的概率把$x$乘$2$,有$(100-p)\%$的概率把$x$加$1$,问最后在二进制下$x$的末尾期望$0$个数 鸽了 ...

  8. 【树状数组】【枚举约数】 - Ambitious Experiment

    给定一个序列,支持以下操作: 对区间[l,r]的每个i,将1i,2i,3i,...这些位置的数都加d. 询问某个位置的数的值. 如果把修改看作对区间[l,r]的每个数+d,那么询问x位置上的数时,显然 ...

  9. map写数据到本地磁盘过程解析----spill和merge

    如上次分析,其实map函数中的context.write()调用过程如下所示: 梳理下调用过程,context的write方法其实是调用了TaskInputOutputContext类的write方法 ...

  10. iOS开发经验——点击屏幕空白处退出键盘

          一种比较简单的点击屏幕空白处退出键盘的方法: 在ViewController中加入如下代码: 1: -(void)touchesBegan:(NSSet *)touches withEve ...