概述

事件中心使用在命名空间和事件中心级别提供的共享访问签名。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. BZOJ 3224: Tyvj 1728 普通平衡树 or 洛谷 P3369 【模板】普通平衡树-Splay树模板题

    3224: Tyvj 1728 普通平衡树 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 22483  Solved: 10130[Submit][S ...

  2. HDU 6326.Problem H. Monster Hunter-贪心(优先队列)+流水线排序+路径压缩、节点合并(并查集) (2018 Multi-University Training Contest 3 1008)

    6326.Problem H. Monster Hunter 题意就是打怪兽,给定一棵 n 个点的树,除 1 外每个点有一只怪兽,打败它需要先消耗 ai点 HP,再恢复 bi点 HP.求从 1 号点出 ...

  3. fmod()函数和modf()函数

    最近从博客上看到了一个fmod函数,结果又蹦出来一个modf函数 fmod()函数: 头文件:#include<math.h> C库函数... fmod()用来对浮点数进行取模(求余),原 ...

  4. leetcode122 Best Time to Buy and Sell Stock

    题意:有一个数组,第i个数据代表的是第i天股票的价格,每天只能先卖出再买进(可以不卖出也可以不买进),求最大收益. 思路:自己去弄几个数组比划比划就知道了,比如[1,2,5,3,6],第一天买进,第二 ...

  5. 「Baltic2015」Network

    题目描述 原文 The government of Byteland has decided that it is time to connect their little country to th ...

  6. POJ 2559 Largest Rectangle in a Histogram(单调栈)

    [题目链接] http://poj.org/problem?id=2559 [题目大意] 给出一些宽度为1的长方形下段对其后横向排列得到的图形,现在给你他们的高度, 求里面包含的最大长方形的面积 [题 ...

  7. laravel中的事件处理

    一.什么是事件处理 事件就是在特地时间.特定地点.发生的特定行为.例如:删除某个用户帖子这个行为后,要通过站短发送信息给帖子所属的用户.这里就有删除帖子事件,发站短是事件后处理. 二.为什么要使用事件 ...

  8. linux-文件中行按照出现次数多少排序

    cat sorttest | sort | uniq -c | sort -k1 sorttest内容如下:

  9. python之pack布局

    #Pack为一布局管理器,可将它视为一个弹性的容器 '''1.一个空的widget'''#不使用pack # -*- coding: cp936 -*- from Tkinter imp ort * ...

  10. <img>元素底部为何有空白及其解决方案

    一.为什么<img>元素底部会有空白? 要理解这个问题,首先要弄明白CSS对于 display: inline 元素的 vertical-align 各个值的含义.vertical-ali ...