Как настроить APNS.Certificate в шаблоне руки

Я использую следующий файл azuredeploy.json для настройки концентратора уведомлений в облаке Azure.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "Gcm.GoogleApiKey": {
            "type": "string",
            "metadata": {
                "description": "Google Cloud Messaging API Key"
            },
            "defaultValue": "AIzaSyAyp9MernKgMS3wFNM3yNWByiP-TaGrqEg"
        },
        "APNS.Certificate": {
            "type": "string",
            "metadata": {
                "description": "A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal"
            },
            "defaultValue": ""
        },
        "APNS.certificateKey": {
            "type": "string",
            "metadata": {
                "description": "The Certificate Key provided by the iOS Provisioning Portal when registering the application"
            },
            "defaultValue": "ce469bf21dfa7b9d595d4999bfaca8a94ea47e46"
        },
        "APNS.endpoint": {
            "type": "string",
            "metadata": {
                "description": "The APNS endpoint to which our service connects. This is one of two values: gateway.sandbox.push.apple.com for the sandbox endpoint or gateway.push.apple.com, for the production endpoint. Any other value is invalid."
            },
            "allowedValues": [
                "gateway.sandbox.push.apple.com",
                "gateway.push.apple.com"
            ],
            "defaultValue": "gateway.push.apple.com"
        }
    },
    "variables": {
        "hubVersion": "[providers('Microsoft.NotificationHubs', 'namespaces').apiVersions[0]]",
        "notificationHubNamespace": "[concat('hubv2', uniqueString(resourceGroup().id))]",
        "notificationHubName": "notificationhub"
    },
    "resources": [
        {
            "name": "[variables('NotificationHubNamespace')]",
            "location": "[resourceGroup().location]",
            "type": "Microsoft.NotificationHubs/namespaces",
            "apiVersion": "[variables('hubVersion')]",
            "comments": "Notification hub namespace",
            "properties": {
                "namespaceType": "NotificationHub"
            },
            "resources": [
                {
                    "name": "[concat(variables('NotificationHubNamespace'),'/',variables('NotificationHubName'))]",
                    "location": "[resourceGroup().location]",
                    "type": "Microsoft.NotificationHubs/namespaces/notificationHubs",
                    "apiVersion": "[variables('hubVersion')]",
                    "properties": {
                        "GcmCredential": {
                            "properties": {
                                "googleApiKey": "[parameters('Gcm.GoogleApiKey')]",
                                "gcmEndpoint": "https://android.googleapis.com/gcm/send"
                            }
                        }
                    },
                    "dependsOn": [
                        "[variables('NotificationHubNamespace')]"
                    ]
                }
            ]
        }
    ],
    "outputs": {
    }
}

Теперь я попытался настроить службу push-уведомлений Apple, также используя следующий фрагмент:

"apnsCredential": {
              "properties": {
                "apnsCertificate": "[parameters('APNS.Certificate')]",
                "certificateKey": "[parameters('APNS.certificateKey')]",
                "endpoint": " gateway.sandbox.push.apple.com or gateway.push.apple.com",
              }
            }

С указанными выше изменениями я выполнил Deploy-AzureResourceGroup.ps1 с помощью командной строки powershell, и при его выполнении я получаю сообщение об ошибке «Неверный запрос».

Может ли кто-нибудь помочь мне решить эту проблему.


person santosh kumar patro    schedule 28.11.2016    source источник
comment
Требуется больше информации, чем «Неверный запрос»   -  person Edward Rixon    schedule 28.11.2016
comment
Вы когда-нибудь заставляли это работать?   -  person oatsoda    schedule 07.07.2017


Ответы (4)


Добавьте правильный APNS.Certificate и APNS.certificateKey. Не удается проверить ваши данные, отсюда и неверный запрос. Вам нужен APNS.Certificate в формате base 64.

APNS.Certificate:

Это сертификат Apple Push Notification в строковом формате base 64.

Вы можете использовать PowerShell для преобразования сертификата следующим образом (затем скопируйте ключ из выходного файла «MyPushCert.txt» и используйте его):

$fileContentBytes = get-content ‘Apple_Certificate.p12’ -Encoding Byte

[System.Convert]::ToBase64String($fileContentBytes) | Out-File ‘MyPushCert.txt’

APNS.certificateKey:

Это пароль, который вы указали при экспорте сертификата (пароль, который вы создали в Apple во время создания сертификата).

person Thor88    schedule 17.05.2018
comment
СПАСИБО! Ваш скрипт Powershell только что вытащил меня из 2 дней устранения неполадок! - person Mark; 30.06.2018
comment
в более новой версии powershell get-content не поддерживает -Encoding Byte вместо этого: $fileContentBytes = get-content ‘Apple_Certificate.p12’ -AsByteStream - person Steven T. Cramer; 07.04.2021

Невозможно точно узнать, что вызвало это, не зная больше о вашей среде/настройке. Согласно этот пост, одна из возможных проблем может заключаться в том, насколько надежен ваш пароль:

После нескольких часов рвения на себе волос и неполучения ничего, кроме «Bad Request», я, наконец, решил использовать более надежный пароль, чем «pass@word1». Будь я проклят, это сработало. Кроме того, подготовка с помощью Azure Resource Manager является асинхронной, поэтому ваши сценарии завершаются намного раньше, чем раньше, поскольку подготовка виртуальных машин осуществляется параллельно.

В сообщении рекомендуется выполнить устранение распространенных ошибок развертывания Azure с помощью Диспетчер ресурсов Azure.

person Nikita R.    schedule 28.11.2016


Мне пришлось использовать PowerShell, чтобы решить эту проблему. Частично идея взята отсюда: https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-deploy-and-manage-powershell

Ниже приведен скрипт, который протестирован локально и работает. Microsoft.Azure.NotificationHubs — используется версия 1.0.9. Мы приняли его для выпуска VSTS в качестве одной из задач/шагов PowerShell после того, как Notification Hub был создан с помощью шаблона ARM.

Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName my-subscription-here

Write-Host "Begin process..."

try
{
    # Make sure to reference the latest version of Microsoft.Azure.NotificationHubs.dll
    Write-Host "Adding the [Microsoft.Azure.NotificationHubs.dll] assembly to the script...";
    $scriptPath = Split-Path (Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path;
    $packagesFolder = $scriptPath + "\packs";
    Write-Host $packagesFolder;
    $assembly = Get-ChildItem $packagesFolder -Include "Microsoft.Azure.NotificationHubs.dll" -Recurse;
    write-Host $assembly.FullName;
    Add-Type -Path $assembly.FullName;

    Write-Host "The [Microsoft.Azure.NotificationHubs.dll] assembly has been successfully added to the script.";

    # Create requered variables
    $HubNamespace = "hub-namespace";
    $HubName = "hub-name";
    $ResourceGroup = "resource-group";

    $GcmApiKey = "api key here";
    # Possible values: gateway.push.apple.com, gateway.sandbox.push.apple.com
    $ApnsEndpoint = "gateway.push.apple.com";
    # A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal
    $ApnsCertificate = "base 64 certificate here";
    $ApnsCertificateKey = "certificate key/password here";

    $GcmCredential = New-Object -TypeName Microsoft.Azure.NotificationHubs.GcmCredential -ArgumentList $GcmApiKey;
    $ApnsCredential = New-Object -TypeName Microsoft.Azure.NotificationHubs.ApnsCredential;
    $ApnsCredential.Endpoint = $ApnsEndpoint;
    $ApnsCredential.ApnsCertificate = $ApnsCertificate;
    $ApnsCredential.CertificateKey = $ApnsCertificateKey;

    # Query the namespace
    $FoundNamespaces = Get-AzureRmNotificationHubsNamespace -Namespace $HubNamespace -ResourceGroup $ResourceGroup

    # Check if the namespace already exists
    if ($FoundNamespaces -and $FoundNamespaces.Length -eq 1)
    {
        $CurrentNamespace = $FoundNamespaces[0];
        Write-Host "The namespace [$HubNamespace] in the [$($CurrentNamespace.Location)] region was found.";

        $HubListKeys = Get-AzureRmNotificationHubListKeys -Namespace $HubNamespace -ResourceGroup $ResourceGroup -NotificationHub $HubName -AuthorizationRule DefaultFullSharedAccessSignature;
        # Check to see if the Notification Hub exists
        if ($HubListKeys)
        {
            # Create the NamespaceManager object used to update the notification hub
            Write-Host "Creating a NamespaceManager object for the [$HubNamespace] namespace...";
            $NamespaceManager = [Microsoft.Azure.NotificationHubs.NamespaceManager]::CreateFromConnectionString($HubListKeys.PrimaryConnectionString);
            Write-Host "NamespaceManager object for the [$HubNamespace] namespace has been successfully created.";

            # Update notification hub with new details
            Write-Host "The [$Path] notification hub already exists in the [$HubNamespace] namespace."  ;
            $NHDescription = $NamespaceManager.GetNotificationHub($HubName);
            $NHDescription.GcmCredential = $GcmCredential;
            $NHDescription.ApnsCredential = $ApnsCredential;
            $NHDescription = $NamespaceManager.UpdateNotificationHub($NHDescription);
            Write-Host "The [$HubName] notification hub was updated";
        }
        else
        {
            Write-Host "The [$HubName] notification hub does not exist."
        }
    }
    else
    {
        Write-Host "The [$HubNamespace] namespace does not exist."
    }
}
catch [System.Exception]
{
    Write-Error($_.Exception.Message)
}

Надеюсь, это поможет кому-то.

person Sergey Chtcherbakov    schedule 12.04.2018