[英]How to generate SAS Token for Azure Event Hubs in Android
How can I generate a SAS Token in an Android application using the sas key from Azure Event Hubs? 如何使用Azure事件中心的sas密钥在Android应用程序中生成SAS令牌?
I found this post, but the libraries are too outdated at this point to be useful: Generate Azure SAS Token on Android 我找到了这篇文章,但是此时这些库已经过时而无用: 在Android上生成Azure SAS令牌
================================================================================ ================================================== ==============================
Imports: 进口:
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
On intent start of background service: 在有意启动后台服务时:
@Override
public void onHandleIntent(Intent intent){
// Now recover the connection URL and the message content from the started intent
url = intent.getStringExtra("URL");
message = intent.getStringExtra("content");
sasKey = intent.getStringExtra("sasKey");
// Generate the sas token
Log.i("sasKey",sasKey);
Log.i("url",url);
String token = generateSasToken();
// Now send the message
Log.i("sasToken",token);
sendMessageOkHttp( message, url, token);
}
Generating the sas token: 生成sas令牌:
private String generateSasToken() {
Log.i(TAG,"generating token");
String targetUri;
String token = null;
Log.i(TAG,"received uri "+url);
try {
targetUri = URLEncoder
.encode(url.toLowerCase(), "UTF-8")
.toLowerCase();
long expiresOnDate = System.currentTimeMillis();
int expiresInMins = 60; // 1 hour
expiresOnDate += expiresInMins * 60 * 1000;
long expires = expiresOnDate / 1000;
String toSign = targetUri + "\n" + expires;
Log.i(TAG,"to Sign " + toSign);
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = sasKey.getBytes("UTF-8");
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(toSign.getBytes("UTF-8"));
// Using android.util.Base64 for Android Studio instead of
// Apache commons codec
String signature = URLEncoder.encode(Base64.encodeToString(rawHmac, Base64.NO_WRAP), "UTF-8");
// Construct authorization string
token = "sig="
+ signature + "&se=" + expires + "&skn=" + "android"+"&sr=" + targetUri;
} catch (Exception e) {
Log.i("sasGeneration","Exception Generating SaS : " + e.getMessage());
}
return token;
}
Sending Message using OkHttp: 使用OkHttp发送消息:
public void sendMessageOkHttp(String dataPacket, String connectionString, String token){
// Instantiate the OkHttp Client
OkHttpClient client = new OkHttpClient();
// Create the body of the message to be send
RequestBody formBody = new FormBody.Builder()
.add("message", dataPacket)
.build();
Log.i("ConnStr",connectionString);
// Now create the request and post it
Request request = new Request.Builder()
.header("Authorization", token)
.url(connectionString)
.post(formBody)
.build();
Log.i(TAG,"about to send message");
// Now try to send the message
try {
Log.i(TAG,"sending message....");
Response response = client.newCall(request).execute();
Log.i(TAG,"message sent");
Log.i("Azure Response",String.valueOf(response.message()));
Log.i("Azure Body",String.valueOf(response.networkResponse()));
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
}
This code compiles and the application runs. 这段代码将编译并运行该应用程序。 However, when I post a message to azure, the response I get is "Unauthorized".
但是,当我向azure发布消息时,得到的响应是“未经授权”。 It seems as though I am generating the token correctly, what could be the problem?
好像我正确生成了令牌,这可能是什么问题?
I have checked the event hub permissions multiple times. 我已多次检查事件中心权限。 And they seem correct too.
而且它们似乎也是正确的。
It sounds like you want to know how to generate a SAS Token of EventHub for Android. 听起来您想知道如何为Android生成EventHub的SAS令牌。 There is an offical tutorial Service Bus authentication with Shared Access Signatures which you can follow to generate the SAS token, and @Jambor-MSFT code for your referenced SO thread should works for your scenario without any Azure Java SDK.
您可以按照官方教程使用共享访问签名进行服务总线身份验证,以生成SAS令牌,并且所引用的SO线程的@ Jambor-MSFT代码应适用于您的方案,而无需任何Azure Java SDK。 Please try, and if any error/exception got when you develop for android, please post for helping us analysis your real issue.
请尝试,如果为Android开发时遇到任何错误/异常,请发布以帮助我们分析您的实际问题。
Here's the helper API from azure event-hubs java library to generate SASToken
(public utility method: SharedAccessSignatureTokenProvider.generateSharedAccessSignature(...)
) : 这是来自azure event-hubs Java库的帮助程序API,用于生成
SASToken
(公共实用程序方法: SharedAccessSignatureTokenProvider.generateSharedAccessSignature(...)
):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.