Azure通知中心 - 使用Java

时间:2018-01-09 15:36:01

标签: java azure push-notification token azure-notificationhub

大家好我正在尝试使用Java中的Azure通知中心发送通知。

这是我使用的代码:

     NotificationHub hub = new NotificationHub("Endpoint=sb://XXXXXXXXXX;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=XXXXXXXXXXXXXXXXX", "myHubName");                                                 
     String message = "{\"data\":{\"msg\":\"Hello from Java!\"}}";
     Notification n = Notification.createGcmNotification(message);
     NotificationOutcome result = hub.sendNotification(n);
     return result.getNotificationId();

问题是当我尝试获取NotificationOutcome对象时,出现无效的授权令牌签名错误。

我认为问题在于令牌的生成,该令牌是使用以下 NotificationHub 类的方法生成的:

private String generateSasToken(URI uri) {
    String targetUri;
    try {
        targetUri = URLEncoder
                .encode(uri.toString().toLowerCase(), "UTF-8")
                .toLowerCase();

        long expiresOnDate = System.currentTimeMillis();
        expiresOnDate += SdkGlobalSettings.getAuthorizationTokenExpirationInMinutes() * 60 * 1000;
        long expires = expiresOnDate / 1000;
        String toSign = targetUri + "\n" + expires;



        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = SasKeyValue.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"));

        // Convert raw bytes to Hex
        String signature = URLEncoder.encode(
                Base64.encodeBase64String(rawHmac), "UTF-8");//

        // construct authorization string
        String token = "SharedAccessSignature sr=" + targetUri + "&sig="
                + signature + "&se=" + expires + "&skn=" + SasKeyName;
        System.out.println(token);
        return token;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我尝试使用php的相同示例,它工作。有什么建议?提前谢谢。

0 个答案:

没有答案