简体   繁体   English

如何为Android中的Azure事件中心生成SAS令牌

[英]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令牌

================================================================================ ================================================== ==============================

Update: Adding code to illustrate how I am generating a sas token and sending messages to Azure - in response to @Peter Pan - MSFT 更新:添加代码以说明我如何生成sas令牌并将消息发送到Azure-响应@Peter Pan-MSFT

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开发时遇到任何错误/异常,请发布以帮助我们分析您的实际问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android上生成Azure SAS令牌 - Generate Azure SAS Token on Android 如何将数据从 android java 发送到 azure 事件中心 - How are send data from android java to azure event hubs 如何在Java / Groovy中为Azure API(Api管理)生成SAS令牌? - How to generate a SAS token for Azure API (Api Management) in Java / Groovy? 如何生成 SAS 令牌并使用它将文件上传到 Azure Blob 存储? - How to generate a SAS token and use it to upload a file to Azure Blob Storage? 为 Java 中的文件生成 Azure SAS 令牌:签名字段格式不正确 - Generate Azure SAS Token for File in Java: Signature fields not well formed 有没有办法以编程方式为 Blob 容器生成 Azure SaS 令牌,即使用户未使用 SaS 令牌 java 进行身份验证 - Is there a way to programmatically generate Azure SaS token for Blob container even when the user is not authenticated with SaS token java 将事件发送到 Azure 事件中心 -> 不允许操作 - Send events to Azure Event Hubs -> Operation not permitted Azure 文件共享 SAS 令牌签名未按预期生成,如何为文件对象生成签名以匹配门户中生成的签名? - Azure File share SAS token signature not generating as expected, How do one generate signature for file object to match the one generated in portal? Azure事件中心中是否有类似于Azure Service Bus主题的内容? - Is there anything similar to Azure Service Bus Topics in Azure Event hubs? 如何在Java中基于SAS令牌访问Azure WASB容器? - How to Access Azure WASB Container Based on SAS Token in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM