0

I am trying to develop an mobile application using asp.net web api and xamarin forms. Getting errors in web api Project:ExpiredProviderToken

I am facing problem to the send the push notification in ios using Apns service.

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate {

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
                                           UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null
                                       );

            UIApplication.SharedApplication.RegisterUserNotificationSettings(notificationSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
        }
        else
        {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
        }
        
        global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
    public override  void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {   
        var IosDeviceToken = UIDevice.CurrentDevice.IdentifierForVendor.ToString();
        if (!string.IsNullOrWhiteSpace(IosDeviceToken))
        {
            IosDeviceToken = IosDeviceToken.Trim('<').Trim('>');
            var model = new IosDevice { IosDeviceId = IosDeviceToken };
            string url = "http://notificationdemo.project-demo.info:8075/DeviceToken/Addtoken";
            HttpClient client = new HttpClient();
            string jsonData = JsonConvert.SerializeObject(model);
            StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var response =  client.PostAsync(url, content);
            var result =  response.Result.StatusCode;
        }
    }
    public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
    {
        var model = new IosDevice { IosDeviceId = error.LocalizedDescription };
        string url = "http://notificationdemo.project-demo.info:8075/DeviceToken/Addtoken";
        HttpClient client = new HttpClient();
        string jsonData = JsonConvert.SerializeObject(model);
        StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        var response = client.PostAsync(url, content);
        var result = response.Result.StatusCode;
        //new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
    }
}

Below code is web api project

public void SendIOSNotification() {

        var options = new ApnsJwtOptions()
        {
            BundleId = "com.itpathsolutions.xamarin",
            
            CertFilePath = @"D:\XamarinForms\demoapp\demoapp\demoapp.iOS\AuthKey_B95M9X635C.p8",
            KeyId = "B95M9X635C",
            TeamId = "M36758127B"
        };
        var apns = ApnsClient.CreateUsingJwt(new HttpClient(new WinHttpHandler()), options);
        var push = new ApplePush(ApplePushType.Alert)
            .AddBadge(1)
            .AddSound("sound.caf")
            .AddCustomProperty("category", "", true)
            .AddCustomProperty("alert", "Good Morning iOS", true)
            .AddCustomProperty("Id", "47474", true)
            .AddCustomProperty("CreatedDate", DateTime.Now.ToString(), true)
            .AddCustomProperty("url", "www.google.com", true)
            .AddCustomProperty("content-available", "1", true)
            .AddToken("CE227D98-4D25-43A6-AEF0-870DB1028772");
        try
        {
            var response = apns.SendAsync(push).Result;
            if (response.IsSuccessful)
            {
                Console.WriteLine("An alert push has been successfully sent!");
            }
            else
            {
                switch (response.Reason)
                {
                    case ApnsResponseReason.BadCertificateEnvironment:
                        
                        break;
                    // TODO: process other reasons we might be interested in
                    default:
                        throw new ArgumentOutOfRangeException(nameof(response.Reason), response.Reason, null);
                }
                Console.WriteLine("Failed to send a push, APNs reported an error: " + response.ReasonString);
            }
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Failed to send a push: HTTP request timed out.");
            throw;
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine("Failed to send a push. HTTP request failed: " + ex);
            throw;
        }
    }

1 Answers1

0

The problem is related to server side .

Check the apple docs .

For security, APNs requires you to refresh your token regularly. Refresh your token no more than once every 20 minutes and no less than once every 60 minutes. APNs rejects any request whose token contains a timestamp that is more than one hour old. Similarly, APNs reports an error if you recreate your tokens more than once every 20 minutes.

On your provider server, set up a recurring task to recreate your token with a current timestamp. Encrypt the token again and attach it to subsequent notification requests.

The docs clear indicates that On your provider server, set up a recurring task to recreate your token with a current timestamp. Encrypt the token again and attach it to subsequent notification requests.

Also check the similar thread : iOS sending push with APNs Auth Key: suddenly "403 Forbidden: {"reason":"InvalidProviderToken"}" .

ColeX
  • 14,062
  • 5
  • 43
  • 240