[AZURE.INCLUDE mobile-services-selector-push-users]
This topic shows you how to send push notifications to an authenticate user on any registered device. Unlike the previous push notification tutorial, this tutorial changes your mobile service to require that a user be authenticated before the client can register with the notification hub for push notifications. Registration is also modified to add a tag based on the assigned user ID. Finally, the server script is updated to send the notification only to the authenticated user instead of to all registrations.
This tutorial walks you through the following process:
- Updating the service to require authentication for registration
- Updating the app to log in before registration
- Testing the app
This tutorial supports both Windows Store and Windows Phone Store apps.
##Prerequisites
Before you start this tutorial, you must have already completed these Mobile Services tutorials:
-
Get started with authentication
Adds a login requirement to the TodoList sample app. -
Get started with push notifications
Configures the TodoList sample app for push notifications by using Notification Hubs.
After you have completed both tutorials, you can prevent unauthenticated users from registering for push notifications from your mobile service.
##Update the service to require authentication to register
[AZURE.INCLUDE mobile-services-javascript-backend-push-notifications-app-users]
Replace the insert function with the following code, then click Save:
function insert(item, user, request) { // Define a payload for the Windows Store toast notification. var payload = '<?xml version="1.0" encoding="utf-8"?><toast><visual>' + '<binding template="ToastText01"><text id="1">' + item.text + '</text></binding></visual></toast>';
// Get the ID of the logged-in user. var userId = user.userId; request.execute({ success: function() { // If the insert succeeds, send a notification to all devices // registered to the logged-in user as a tag. push.wns.send(userId, payload, 'wns/toast', { success: function(pushResponse) { console.log("Sent push:", pushResponse); request.respond(); }, error: function (pushResponse) { console.log("Error Sending push:", pushResponse); request.respond(500, { error: pushResponse }); } }); } });
}
This insert script uses the user ID tag to send a push notification (with the text of the inserted item) to all Windows Store app registrations created by the logged-in user.
##Update the app to log in before registration
[AZURE.INCLUDE mobile-services-windows-store-javascript-push-notifications-app-users]
[AZURE.INCLUDE mobile-services-windows-test-push-users]